这些天我一直在学习D3。非常有趣。 有一个问题:
如果在update()中有一个字母,如“o”,那么enter()有两个相同的字母“o o”,而当前的update()只有一个“o”。 但是当进入update()时,如何使enter()中的重复字母仍然存在?
查看http://jsfiddle.net/2pB5J/5/ 在这段代码中,我希望“54321” - > “有一个o” - > “有两个oo”
var alphabet = "5 4 3 2 1".split(" ");
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) + ")");
function update(data) {
// DATA JOIN
// Join new data with old elements, if any.
var text = svg.selectAll("text")
.data(data, function(d) { return d; });
// UPDATE
// Update old elements as needed.
text.attr("class", "update")
.transition()
.duration(750)
.attr("x", function(d, i) { return i * 30 ; });
// ENTER
// Create new elements as needed.
text.enter().append("text")
.attr("class", "enter")
.attr("dy", ".35em")
.attr("y", 70)
.attr("x", function(d, i) { return i * 30; })
.style("fill-opacity", 1e-6)
.text(function(d) { return d; })
.transition()
.duration(750)
.attr("y", 0)
.style("fill-opacity", 1);
// EXIT
// Remove old elements as needed.
text.exit()
.attr("class", "exit")
.transition()
.duration(750)
.attr("y", -60)
.attr("x", 10)
.style("fill-opacity", 1e-6)
.remove();
}
// The initial display.
update(alphabet);
var i = 0;
words = [
"There is an o".split(""),
"There are two oo".split(""),
];
setInterval(function() {
update(words[i]);
i++
//if(i == 3) {
// i = 0;
//}
}, 1500);
// Shuffles the input array.
function shuffle(array) {
var m = array.length, t, i;
while (m) {
i = Math.floor(Math.random() * m--);
t = array[m], array[m] = array[i], array[i] = t;
}
return array;
}
答案 0 :(得分:0)
通过
var text = svg.selectAll("text")
.data(data, function(d) { return d; });
您告诉d3将该字母视为数据的ID。然后有多个o将导致相同的id" o"在你的数据中多次出现这种情况当然会破坏整个事情。
把这封信和它的位置作为身份怎么样?这将是:
var text = svg.selectAll("text")
.data(data, function(d, i) { return d+i.toString(); });
旁注: 您的setInterval函数将尝试访问不存在的将导致错误的数组索引。尝试类似:
var updateInterval = setInterval(function() {
alert(words[i]);
update(words[i]);
i++
if(i === 2) {
clearInterval(updateInterval);
}
}, 1500);
这就是它的样子: http://jsfiddle.net/2pB5J/8/