[英]d3: update dataset not updating the DOM
I want to create a list using D3 using the following data: 我想使用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'
});
Which works. 哪个有效。 Now after some time, I change the data
现在过了一段时间,我更改了数据
dataSet[0].value = 40;
dataSet[1].value = 30;
dataSet[2].value = 20;
dataSet[3].value = 10;
and I would like to draw the list again: 我想再次绘制清单:
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);
However, this list is not really updated. 但是,此列表并未真正更新。 Any suggestions how to fix this ?
任何建议如何解决这个问题?
This can be accomplished by removing the existing circles first by calling: 这可以通过首先调用以下方法删除现有的圈子来完成:
svg.selectAll('circle').remove()
and then going through adding them again with different data set. 然后再通过不同的数据集再次添加它们。 I updated your fiddle http://jsfiddle.net/Q5Jag/1183/
我更新了您的小提琴http://jsfiddle.net/Q5Jag/1183/
Hope this helps. 希望这可以帮助。
Here is same fiddle with some enter and exit animations http://jsfiddle.net/Q5Jag/1184/ 这是带有一些输入和退出动画的小提琴, http://jsfiddle.net/Q5Jag/1184/
The problem is that you're handling only the enter selection, which will be empty on update -- you need to handle the update selection: 问题是您只处理输入选择,更新时将为空-您需要处理更新选择:
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'
});
Updated fiddle here . 在这里更新了小提琴。 For more information on the different selections, have a look at this tutorial .
有关不同选择的更多信息,请参阅本教程 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.