[英]d3: update dataset not updating the DOM
我想使用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);
但是,此列表並未真正更新。 任何建議如何解決這個問題?
您需要清除svg.html('');
在setTimeout
演示
這可以通過首先調用以下方法刪除現有的圈子來完成:
svg.selectAll('circle').remove()
然后再通過不同的數據集再次添加它們。 我更新了您的小提琴http://jsfiddle.net/Q5Jag/1183/
希望這可以幫助。
這是帶有一些輸入和退出動畫的小提琴, http://jsfiddle.net/Q5Jag/1184/
問題是您只處理輸入選擇,更新時將為空-您需要處理更新選擇:
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'
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.