简体   繁体   中英

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/

the idea is that I should have ag elemennt with a rect and a text for every data object attribute, like:

<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. On the example you can see the problem ( http://jsfiddle.net/k8sftbez/ )

这是因为您的更新功能实际上还包括创建条形图,为了使它们仅更改颜色,您应该具有两个单独的功能,一个用于添加对象,另一个用于更新(例如,您可以附加没有任何属性的矩形的函数以及为矩形设置样式的更新函数)

In the end, I've fixed modifing the update function like this: 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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM