2013-01-08 87 views
2

我有一個按鈕,它在圖形上的那條線上繪製一條線和一些點。我有第二個按鈕,刪除線條和點。我試圖對這兩個函數使用相同的按鈕。D3.js的切換按鈕

我有一些困難。有沒有人見過這樣的事情?

這是我的兩個功能。提前致謝!

//Draws line and dots 
d3.select(".button1").on("click", function(){ 
    var path = svg.append("path") // Add the valueline path. 
      .attr("class", "line") 
      .attr("d", valueline(data)) 
      .attr("stroke", "steelblue") 
      .attr("stroke-width", "5") 
      .attr("fill", "black"); 


svg.selectAll("dot") 
    .data(data) 
.enter().append("circle") 
    .attr("class", "firstDots") 
    .attr("r", 5) 
    .attr("cx", function(d) { return x(d.date); }) 
    .attr("cy", function(d) { return y(d.close); }) 

     var totalLength = path.node().getTotalLength(); 


    path 
    .attr("stroke-dasharray", totalLength + "30" * 30) 
    .attr("stroke-dashoffset", totalLength) 
    .transition() 
     .duration(2000) 
     .ease("linear") 
     .attr("stroke-dashoffset", 0); 

    //Removes line and dots 
    d3.select(".button2").on("click", function(){ 
     path.remove(); 

    var removeDot = svg.selectAll(".firstDots") 
       .remove(); 

    }); 

}); 

起初,我嘗試在每個點擊事件上來回傳遞按鈕的類,它適用於繪圖和刪除。但只有一次,所以我無法第二次劃清界限。

+0

你可以發佈一個完整的例子來[的jsfiddle(http://jsfiddle.net/)嗎? –

+0

您需要在'.button1'單擊事件處理函數之外移動'.button2'單擊事件處理程序的分配,否則每次點擊'.button1'時都會綁定另一個'.button2'處理程序。 – MikeM

回答

3

你可以移動path變量的事件處理程序之外:

<!DOCTYPE html> 
<html> 
<head> 
    <script src='http://d3js.org/d3.v3.min.js'></script> 
</head> 
<body> 
    <button>Toggle path</button> 
    <script> 
    var svg = d3.select('body') 
     .append('svg') 
     .attr('width', 500) 
     .attr('height', 250); 

    var path; 

    d3.select('button').on('click', function() { 

     if (path) { 
      path.remove(); 
      // Remove dots 
      path = null; 
     } else { 
      path = svg.append('path') 
       .attr('class', 'line') 
       .attr('d', 'M100,150 Q200,25 300,150 T500,150') 
       .attr('stroke', 'steelblue') 
       .attr('stroke-width', '5') 
       .attr('fill', 'black'); 
      // Add dots etc. 
     }   
    }); 
    </script> 
</body> 
</html> 
+0

@Daft。請現在嘗試。如果它不起作用,請發佈其餘的代碼。 – MikeM

+1

jsfiddle上面的代碼。 http://jsfiddle.net/SzVrs/10/ – mg1075

+0

jsfiddle編輯後回答[jsfiddle.net/SzVrs/11/](http://jsfiddle.net/SzVrs/11/) – MikeM