gui*_*rin 2 javascript arrays selectall button d3.js
我想在d3中创建几个按钮.为了有一个更清晰的代码我想在数组中添加他们的名字.
我有以下代码,但它不起作用:
var buttonNames = ["button 1", "button 2", "button 3", "button 4"]
d3.select("body").selectAll("input").data(buttonNames).enter().append("input").attr("type","button").attr("class","button").attr("value", function d(){return d;} )
Run Code Online (Sandbox Code Playgroud)
在此先感谢您的回复.
你的函数定义中有一个拼写错误.
.attr("value", function d(){return d;} )
Run Code Online (Sandbox Code Playgroud)
应该
.attr("value", function (d){return d;} )
Run Code Online (Sandbox Code Playgroud)
注意,这d
是函数的参数,必须在括号内.
小智 5
这就是我创建多个按钮的方法。
d3.select("#some_id")
.append("div")
.attr("class","some_other_id")
.each(function(d) {
for (var i = 1; i < number_to_duplicate; i++) {
d3.select("#some_other_id")
.append("button")
.attr("type","button")
.attr("class","btn-btn")
.attr("id",function(d) { return 'button '+i;})
.append("div")
.attr("class","label")
.text(function(d) { return 'button '+i;})
Run Code Online (Sandbox Code Playgroud)
我创建了一个 div 和一个 .each(function)。在函数中,for 循环创建按钮。这为我提供了所需数量的按钮 - number_to_duplicate - 每个按钮都有单独的 id。当然,我可以修改它并制作更多具有相同或不同属性的按钮,将它们附加到不同的 Yet_another_id 元素。
如果需要,可以在循环外的其他地方完成标签。这是我可怜人的“纽扣工厂”。请发表评论,无论是正面的还是负面的——供我学习。