2017-02-22 94 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/