2016-03-01 70 views
2

我有一個條形圖,其中使一個單獨的類「欄中的」 +數的各欄:如何使用函數更改d3.selectAll()內部的內容?

chart.selectAll(".bar") 
     .attr("class", function(d) { return "bar" + chart_x(d.year); }) 

如果chart_x(d.year)5,那麼它給出了一個rect酒吧bar5類。迄今爲止所有的工作都很好

現在我需要訪問每個酒吧d3.selectAll()爲了改變每個酒吧的風格。這是我試過的,但它不起作用。

d3.selectAll(function (d) {return ".bar" + chart2_x(d.year); }).style("stroke", "red"); 

我需要它做什麼,例如,如果類是".bar5",是d3.selectAll(".bar5").style("stroke", "red");5是可變的。

任何人都可以幫忙嗎?

回答

1

有幾個方法可以做到你想要什麼:

可以使用filter()功能。但是,在這種情況下,您需要確保不要在類名中使用後綴。因此,假設你只使用bar作爲類,你可以做這樣的事情:

var yearToBeSelected = 5; 
d3.selectAll(".bar") 
.filter(function (d) { 
    return chart2_x(d.year) == yearToBeSelected; 
}) 
.style("stroke", "red"); 

但是,如果這是一個要求,即類名的格式爲bar<number>,你可以選擇所有的選擇使用正則表達式像這樣

var yearToBeSelected = 5; 

//selects all elements with class starting with bar 
d3.selectAll("*[class^=bar]") 
.filter(function (d) { 
    return chart2_x(d.year) == yearToBeSelected; 
}) 
.style("stroke", "red");