javascript - d3 : update dataset not updating the DOM

标签 javascript d3.js

我想使用 D3 使用以下数据创建一个列表:

var dataSet = [
    { label: 'a', value: 10},
    { label: 'b', value: 20},
    { label: 'c', value: 30},
    { label: 'd', value: 40}
];

var circle = svg.selectAll('circle')
    .data(dataSet)
    .enter()
    .append('circle')
    .attr({
        r:function(d){ return d.value },
        cx:function(d, i){ return i * 100 + 50 },
        cy:50,
        fill: 'red'
    });

这有效。一段时间后,我更改了数据

dataSet[0].value = 40;
dataSet[1].value = 30;
dataSet[2].value = 20;
dataSet[3].value = 10;

我想再次绘制列表:

setTimeout(function () {
    var circle = svg.selectAll('circle')
      .data(dataSet, function (d) {
          return d.label;   
      })
     .sort(function (a,b){ return d3.ascending(a.value, b.value);})
     .enter()
     .append('circle')
     .attr({
        r:function(d){ return d.value },
        cx:function(d, i){ return i * 100 + 50 },
        cy:50,
        fill: 'red'
     });
},1000);

DEMO

但是,这个列表并没有真正更新。有什么建议如何解决这个问题吗?

最佳答案

问题是您只处理输入选择,更新时该选择将为空 - 您需要处理更新选择:

svg.selectAll('circle')
.data(dataSet, function (d) {
    return d.label;   
})
.sort(function (a,b){ return d3.ascending(a.value, b.value);})
.transition()
.attr({
    r:function(d){ return d.value },
    cx:function(d, i){ return i * 100 + 50 },
    cy:50,
    fill: 'red'
});

更新了 fiddle here 。有关不同选择的更多信息,请查看 this tutorial .

关于javascript - d3 : update dataset not updating the DOM,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31206515/

相关文章:

javascript - 水平条形图 d3.js 不显示标签

javascript - 绑定(bind)数据在 d3.js 中不起作用

javascript - 如何检查具有相同ID的div的内容,并为包含特定文本的div添加一个类?

javascript - Tensorflow Js 中多时间序列预测的最佳方法

javascript - jshint 错误 : Redefinition of '$'

javascript - 谁能解释 D3 中 delaunay 实现的 alpha 过滤?

javascript - 使用 JSON 更新 D3 饼图

javascript - 邮寄到 : anchor links unloading html5 video in Chrome

javascript - 使用 JavaScript 提取由与数字无关的双引号括起来的子字符串

javascript - 使用 D3.js 的分层力图