2

グラフ上の線とその線上にいくつかの点を描くボタンがあります。線と点を削除する2番目のボタンがあります。両方の機能に同じボタンを使用しようとしています。

私はそれにいくつかの問題を抱えています。誰かが以前にこのようなものを見たことがありますか?

これが私の2つの機能です。前もって感謝します!

 //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();

     });

});

最初は、クリックイベントごとにボタンのクラスを前後に渡してみましたが、描画と削除に使用できます。でも一度だけなので、二度目は線を引くことができません。

4

1 に答える 1

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>
于 2013-01-08T18:54:19.387 に答える