如何使用d3.js选择为每个数据元素创建多个相邻节点 [英] How to create multiple adjacent nodes per data element with d3.js selections
问题描述
使用以下数据:
var days = ["Sun", "Mon", "Tues", "Wed", "Thur", "Fri", "Sat"];
我需要让html结构变成:
I need to have the html structure become:
<div>
<input id="day0" type="checkbox">
<label for="day0">Sun</label>
<input id="day1" type="checkbox">
<label for="day1">Mon</label>
.... Etc
</div>
目前我当前失败的解决方案是:
Currently my current failed solution is:
var selection = d3.select("div");
var enter = selection.selectAll("input").data(days).enter()
enter.append("input")
.attr("type","checkbox")
.attr("id",function(d,i){ return "day"+i;})
enter.append("label")
.attr("for",function(d,i){ return "day"+i;})
.text(function(d,i){return daysAbbr[i];})
这给我一个不正确的dom:
Which gives me an incorrect dom of:
<div>
<input id="day0" type="checkbox">
<input id="day1" type="checkbox">
.... Etc
<label for="day0">Sun</label>
<label for="day1">Mon</label>
.... Etc
</div>
如何创建所有这些相邻的兄弟姐妹?
How would I go about creating all of these adjacent siblings?
推荐答案
你得到这个结构,因为D3使用选择进行排序的批处理。
You're getting this structure because D3 does a batch processing of sorts with the selections. That is, each operation you perform on a selection is performed on all the elements at once.
在你的情况下,你可能想要使用 .each()
允许您调用选择的每个元素上的函数。代码看起来像这样。
In your case, you probably want to use .each()
, which allows you to call a function on each element of the selection. The code would look something like this.
var enter = selection.selectAll("input").data(days).enter();
enter.each(function() {
selection.append("input");
selection.append("label");
});
因为 .enter()
选择没有定义 .each()
。
在你的情况下,一个更好的解决方案是封装你想要出现在另一个 div
虽然。这将允许您以更标准的方式使用D3。代码看起来像这样。
A better solution in your case would be to encapsulate the elements you want to appear together in another div
though. This would allow you to use D3 in a more standard way. The code would look like this.
var enter = selection.selectAll("input").data(days).enter();
var divs = enter().append("div");
divs.append("input");
divs.append("label");
这篇关于如何使用d3.js选择为每个数据元素创建多个相邻节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!