使用D3创建DIV的动态列表 [英] Creating a dynamic list of DIVs with D3
问题描述
我一直在使用 D3 创建精美的动画图表,例子很棒。但是,我试图做一些看起来更基本的东西,并且麻烦 - 将数据绑定到一个简单的DIV列表。
I have been using D3 to create fancy animated charts, and the examples are great. However, I'm trying to do something seemingly a lot more basic, and having trouble - binding data to a simple list of DIVs.
我设置了 enter()
来初始化opacity 0, transition()
可将其淡出并将其删除。 enter()
和 exit()
似乎工作正常 - 但是,当更新包含已经存在的元素列表,它似乎被部分删除 - 包含DIV保留,但内容消失。我不明白为什么元素的内容会以这种方式改变。
I set up enter()
to initialize elements at opacity 0, transition()
to fade them in, and exit()
to fade them out and remove them. enter()
and exit()
seem to be working fine - however, when an update contains an existing element already in the list, it seems to get partially removed - the containing DIV remains, but the contents disappear. I can't understand why the contents of the element would get changed in this way.
我的代码如下:
var data = [...];
sorted = data.sort(function(a, b) { return d3.descending(a.id, b.id); });
var tweet = tweetsBox
.selectAll('div')
.data(sorted, function(d) { return d.id; });
var enterDiv = tweet.enter()
.append("div")
.attr("class", "tweetdiv")
.style("opacity", 0);
enterDiv.append("div")
.attr("class", "username")
.text(function(d) { return "@" + d.username });
enterDiv.append("div")
.attr("class", "displayname")
.text(function(d) { return d.displayname });
enterDiv.append("div")
.attr("class", "date")
.text(function(d) { return d.date });
enterDiv.append("div")
.attr("class", "text")
.text(function(d) { return d.text });
tweet.transition()
.delay(200)
.style("opacity", 1);
tweet.exit()
.transition()
.duration(200)
.style("opacity", 0)
.remove();
I also set up a jsFiddle here demonstrating the issue.
推荐答案
问题在于,选择您创建的 div
,但每个数据元素创建多个 div
。更新时,d3尝试将数据与嵌套的 div
匹配。由于您已经为顶层 div
分配了一个特殊类,所以修复非常简单。替换
The problem is that you're selecting the div
s you created, but create more than one div
per data element. When updating, d3 tries to match the data to the nested div
s. As you're already assigning a special class to the top-level div
s, the fix is very simple. Replace
.selectAll('div')
与
.selectAll('.tweetdiv')
这篇关于使用D3创建DIV的动态列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!