现有的三角形无法删除

时间:2017-01-16 14:40:03

标签: d3.js

我用D3.js中的数据绑定三角形。但是数据不能删除triganle。矩形没问题。附上完整的代码!



var svg = d3.select("body").append("svg")
  .attr("width",  250)
  .attr("height", 250);

function render(data){       
  var tris = svg.selectAll("tri").data(data);
  tris.enter().append("path");
  tris.attr("d", function(d) {
    var x1 = (0.4 - 0.2 * (d - 1)) * 250, y1 = 0.3 * 250;
    var x2 = (0.5 - 0.2 * (d - 1)) * 250, y2 = 0.1 * 250;
    var x3 = (0.6 - 0.2 * (d - 1)) * 250, y3 = 0.3 * 250;
    return "M" + x1 + " " + y1 + " L" + x2 + " " + y2 + " L" + x3 + " " + y3 + "Z";
    });
  tris.exit().remove();
        
  var rects = svg.selectAll("rect").data(data);
  rects.enter().append("rect");
  rects.attr("y", 50)
    .attr("width",  20)
    .attr("height", 20)
    .attr("x", function(d) { return d * 40; });
  rects.exit().remove();
}
render([1, 2, 3]);
render([1, 2]); 
render([1]);

<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:2)

没有名为<tri>的SVG元素。您的输入选择有效,因为您可以在数据绑定功能中选择任何。因为没有任何名字&#34; tri&#34;在整个DOM中(无论是标签,类,ID,等等......),您的输入选择从不为空,退出选择从不填充

话虽如此,一个简单的解决方案是按班级选择......

var tris = svg.selectAll(".tri").data(data);

在输入选择中设置此类:

tris.enter().append("path").attr("class", "tri");

以下是包含更改的代码:

&#13;
&#13;
var svg = d3.select("body").append("svg")
  .attr("width",  250)
  .attr("height", 250);

function render(data){       
  var tris = svg.selectAll(".tri").data(data);
  tris.enter().append("path").attr("class","tri");
  tris.attr("d", function(d) {
    var x1 = (0.4 - 0.2 * (d - 1)) * 250, y1 = 0.3 * 250;
    var x2 = (0.5 - 0.2 * (d - 1)) * 250, y2 = 0.1 * 250;
    var x3 = (0.6 - 0.2 * (d - 1)) * 250, y3 = 0.3 * 250;
    return "M" + x1 + " " + y1 + " L" + x2 + " " + y2 + " L" + x3 + " " + y3 + "Z";
    });
  tris.exit().remove();
        
  var rects = svg.selectAll("rect").data(data);
  rects.enter().append("rect");
  rects.attr("y", 50)
    .attr("width",  20)
    .attr("height", 20)
    .attr("x", function(d) { return d * 40; });
  rects.exit().remove();
}

render([1, 2, 3]);
setTimeout(() => render([1, 2]), 1000); 
setTimeout(() => render([1]), 2000)
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
&#13;
&#13;
&#13;