[英]d3 wrongly append dom elements on data update
I'm tryng to use d3 and his enter/exit pattern to update my bar grap here you can see the current results http://jsfiddle.net/k8sftbez/ 我正在尝试使用d3和他的进入/退出模式来更新我的条形图,在这里您可以看到当前结果http://jsfiddle.net/k8sftbez/
the idea is that I should have ag elemennt with a rect and a text for every data object attribute, like: 我的想法是,我应该为每个数据对象属性添加一个带有rect和文本的元素,例如:
<g>
<rect></rect>
<text></text>
</g>
the graph is created as aspected but my problem is when I try to update the bar color (I do it on mouseover), instead of updating the currents rect and text tag, it appends 2 new tags on every update. 该图形是按方面创建的,但是我的问题是,当我尝试更新条形颜色时(我在鼠标悬停时执行此操作),而不是更新当前的rect和text标签,而是在每次更新时都添加了2个新标签。 On the example you can see the problem ( http://jsfiddle.net/k8sftbez/ )
在示例中,您可以看到问题( http://jsfiddle.net/k8sftbez/ )
这是因为您的更新功能实际上还包括创建条形图,为了使它们仅更改颜色,您应该具有两个单独的功能,一个用于添加对象,另一个用于更新(例如,您可以附加没有任何属性的矩形的函数以及为矩形设置样式的更新函数)
In the end, I've fixed modifing the update function like this: http://jsfiddle.net/5ft6uL6k/ 最后,我修复了如下修改更新功能的问题: http : //jsfiddle.net/5ft6uL6k/
I think is the more elegant way, using the placeholder and update them. 我认为使用占位符并更新它们是一种更优雅的方法。
basically this part: 基本上这部分:
var bar = chart.selectAll("g").data(data)
bar.enter().append("g").attr("transform", function(d, i) {
return "translate(0," + i * barHeight + ")";
})
var valueBar = bar.append("rect");
valueBar
.attr(valueBarValues.attr)
.attr("width", function(d){return x(d.value)})
.style(valueBarValues.style);
bar.append("text")
.attr(textConfig.attrs)
.style(textConfig.style)
.text(function(d) { return d.name; })
bar.exit().remove();
is changed like this: 更改如下:
var bar = chart.selectAll("g").data(data)
var barEnter = bar.enter().append("g");
barEnter.attr("transform", function(d, i) {
return "translate(0," + i * barHeight + ")";
});
barEnter.append("rect");
barEnter.append("text");
var textBar = bar.selectAll("text")
textBar
.attr(textConfig.attrs)
.style(textConfig.style)
.text(function(d) { return d.name; })
var valueBar = bar.selectAll("rect");
valueBar
.attr(valueBarValues.attr)
.attr("width", function(d){return x(d.value)})
.style(valueBarValues.style);
bar.exit().remove();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.