2017-02-22 89 views
2

This D3 js example显示所有代码以生成可切换的多线图。图中的每一行包含现有数据点的点。D3 js多线图切换点开/关

尽管可以打开/关闭这些线条,但这些点仍然停滞不前。我想为切换工作打开/关闭行&与同一行关联的点。

我怀疑svg.append("text")是需要代码更新的部分,以使点与线一起打开/关闭。

这里是现有的代码snipet打开/关闭线图,但它不打开/关闭点。

svg.append("text") 
     .attr("x", (legendSpace/2)+i*legendSpace) // space legend 
     .attr("y", height + (margin.bottom/2)+ 5) 
     .attr("class", "legend") // style the legend 
     .style("font-size","15px") // Change the font size 
     .style("font-weight", "bold") // Change the font to bold 
     .style("text-anchor", "middle") // center the legend 
     .style("fill", function() { // Add the colours dynamically 
      return d.color = color(d.key); }) 
     .on("click", function(){ 
      // Determine if current line is visible 
      var active = d.active ? false : true, 
      newOpacity = active ? 0 : 1; 
      // Hide or show the elements based on the ID 
      d3.select("#tag"+d.key.replace(/\s+/g, '')) 
       .transition().duration(100) 
       .style("opacity", newOpacity); 
      // Update whether or not the elements are active 
      d.active = active; 
      }) 
     .text(d.key); 

请帮忙。

回答

2

ID是唯一。您不能为几个不同的DOM元素设置相同的ID。

解决方案:改为设置类别。

对于线:

.attr("class", 'tag'+d.key.replace(/\s+/g, '')) 

而对于圈:

.attr("class", d=>'tag'+d.symbol.replace(/\s+/g, '')) 

然后,就上点击事件的类(使用selectAll,不select):

d3.selectAll(".tag"+d.key.replace(/\s+/g, '')) 

这里是更新的小提琴:http://jsfiddle.net/gx4zc8tq/