Javascript D3对象恒定性不适用于键功能。每次输入和更新包含所有元素
试图实现对象恒常性。其概念是使用文本中的渐进短语作为数据,用文本更新DOMJavascript D3对象恒定性不适用于键功能。每次输入和更新包含所有元素,javascript,d3.js,Javascript,D3.js,试图实现对象恒常性。其概念是使用文本中的渐进短语作为数据,用文本更新DOM //////////////////////////////////////////////////////////////////////// // We need a way to change the data to illustrate the update pattern. // We use lyrics to do this. Below is code for updating the data. //
////////////////////////////////////////////////////////////////////////
// We need a way to change the data to illustrate the update pattern.
// We use lyrics to do this. Below is code for updating the data.
////////////////////////////////////////////////////////////////////////
var data = [];
function lyricIterator(phrases) {
var nextIndex = 0;
return {
next: function(){
if (nextIndex >= (phrases.length - 1)) {
nextIndex = 0;
debugger;
} else {
nextIndex = nextIndex + 1;
}
// console.log(phrases.slice(nextIndex - 1, nextIndex + 2));
return phrases.slice(nextIndex - 1, nextIndex + 2);
}
}
}
var lyrics = [
{i : 0, phrase : "Row, row, row your boat,"},
{i : 1, phrase : "Gently down the stream."},
{i : 2, phrase : "Merrily, merrily, merrily, merrily,"},
{i : 3, phrase : "Life is but a dream."}
]
// Instantiate an iterator for our lyrics
var rrryb = lyricIterator(lyrics)
/////////////
// Set up
//////////////
var width = 960,
height = 500;
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height)
.append("g")
.attr("transform", "translate(32," + (height / 2) + ")");
//////////////////////////
// Redraw the elements
/////////////////////////
function update() {
data = rrryb.next()
var phrases = svg.selectAll("phrases")
.data(data, function(d) { return d.i; });
console.log("Update")
console.log(phrases)
console.log("Enter")
console.log(phrases.enter())
console.log("Exit")
console.log(phrases.exit())
phrases.exit().remove();
// UPDATE
// Update old elements as needed.
phrases.attr("class", "update");
phrases.enter().append("text")
.attr("class", "enter")
.attr("dy", function(d, i) { return i * 32; })
.attr("dx", ".35em");
phrases.text(function(d) { return d.phrase; })
}
////////////////////////////////////////////////////
// Register the function to run at some interval
///////////////////////////////////////////////////
setInterval(function() {
update()
}, 1500);
我将其作为控制台的输出(每次输入并更新所有元素):
输出的只是堆叠在一起的文本
而不是这个:
var phrases = svg.selectAll("phrases")//there is no DOM as phrases it will return an empty selection always.
.data(data, function(d) { return d.i; });
应该是这样的:
var phrases = svg.selectAll("text")//select all the text
.data(data, function(d) { return d.i; });
原因:这将返回一个空的选择始终svg。selectAll(“短语”)
这就是为什么它总是追加
在第二种情况下,它将返回文本DOM的选择
工作代码现场显示。非常感谢。