簡體   English   中英

d3錯誤地在數據更新上附加了dom元素

[英]d3 wrongly append dom elements on data update

我正在嘗試使用d3和他的進入/退出模式來更新我的條形圖,在這里您可以看到當前結果http://jsfiddle.net/k8sftbez/

我的想法是,我應該為每個數據對象屬性添加一個帶有rect和文本的元素,例如:

<g>
  <rect></rect>
  <text></text>
</g>

該圖形是按方面創建的,但是我的問題是,當我嘗試更新條形顏色時(我在鼠標懸停時執行此操作),而不是更新當前的rect和text標簽,而是在每次更新時都添加了2個新標簽。 在示例中,您可以看到問題( http://jsfiddle.net/k8sftbez/

這是因為您的更新功能實際上還包括創建條形圖,為了使它們僅更改顏色,您應該具有兩個單獨的功能,一個用於添加對象,另一個用於更新(例如,您可以附加沒有任何屬性的矩形的函數以及為矩形設置樣式的更新函數)

最后,我修復了如下修改更新功能的問題: http : //jsfiddle.net/5ft6uL6k/

我認為使用占位符並更新它們是一種更優雅的方法。

基本上這部分:

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

更改如下:

    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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM