好的,我一直在尝试根据数据集中的列数动态地将一些复选框附加到 div。所以我认为 d3 将是要走的路,只需将输入附加适当的属性和一些文本,用于根据数据确定的标签。我试过下面的代码;
d3.select("body").selectAll("input")
.data([11, 22, 33, 44])
.enter().append("input")
.attr("checked", true)
.attr("type", "checkbox")
.attr("id", function(d,i) { return i; })
.attr("onClick", "change(this)")
.attr("for", function(d,i) { return i; })
.text(function(d) { return d; });
Run Code Online (Sandbox Code Playgroud)
这导致页面上有 4 个复选框,但没有标签。
真正奇怪的是,当我检查元素时,生成的 html 似乎是我所追求的,如下所示。
<input checked="true" type="checkbox" id="0" onclick="change(this)" for="0">11</input>
<input checked="true" type="checkbox" id="1" onclick="change(this)" for="1">22</input>
<input checked="true" type="checkbox" id="2" onclick="change(this)" for="2">33</input>
<input checked="true" type="checkbox" id="3" onclick="change(this)" for="3">44</input>
Run Code Online (Sandbox Code Playgroud)
当我在页面上使用它时,我得到的正是我想要的。
我确定我错过了一些非常简单的东西,但对于我的生活,我看不到它是什么。任何帮助感激地接受!
您的主要问题是您不能在这样的<input>标签之间放置文本。它们像<input />. 您应该<label>为该文本使用该元素。
另一个问题是 ID必须以字母开头(至少在 HTML5 之前),所以id="1"不会起作用,但id=a1"会起作用。
也就是说,这段代码解决了这两个问题
d3.select("body").selectAll("input")
.data([11, 22, 33, 44])
.enter()
.append('label')
.attr('for',function(d,i){ return 'a'+i; })
.text(function(d) { return d; })
.append("input")
.attr("checked", true)
.attr("type", "checkbox")
.attr("id", function(d,i) { return 'a'+i; })
.attr("onClick", "change(this)");
Run Code Online (Sandbox Code Playgroud)