我想使用数据集创建一组单选按钮并将特定按钮标记为默认值。有两个问题:
首先,文本与单选按钮的左侧对齐,但通常会看到它在右侧,在 HTML 中如下所示:
<form><label><input type="radio"...> First label<input...></label>
我尝试在设置输入标签后在标签集合上使用 D3 来放置标签文本,但这似乎会覆盖输入标签。
其次,默认按钮仅用不合格的属性名称“checked”或“selected”来指示。我已经在代码的最后一行中尝试过此操作,但它似乎不起作用。
这是现在的代码,associated JSFiddle .
var shapeData = ["Arrow", "Cross", "Hexagon", "Star", "Triangle"],
j = 3; // Choose the star as default
// Create the shape selectors
var form = d3.select("body").append("form");
labels = form.selectAll("label")
.data(shapeData)
.enter()
.append("label")
.text(function(d) {return d;})
.append("input")
.attr({
type: "radio",
class: "shape",
name: "mode",
value: function(d, i) {return i;}
})
.attr(function(d, i) {return i==j?"selected":null;});
最佳答案
首先,为了使标签/输入正确排序,您应该避免将输入嵌套在标签内。因此,您可以在 Enter 上插入一个 div 或 span,然后在 span 内添加标签和输入,如下所示:
var labelEnter = form.selectAll("span")
.data(shapeData)
.enter().append("span");
labelEnter.append("input")
.attr({
type: "radio",
class: "shape",
name: "mode",
value: function(d, i) {return i;}
})
.property("checked", function(d, i) {
return (i===j);
});
labelEnter.append("label").text(function(d) {return d;});
虽然这有点作弊,但我相信这是在这里做你想做的事情的唯一方法。我认为没有任何方法可以指定相对于 D3 中元素的子元素附加文本的位置。如果要将元素添加为子元素,则可以使用append() 与insert() 来指定是追加到子元素列表的末尾还是插入到开头。也许为文本添加类似的功能(如果可能的话)将是一个值得提交给 D3 的拉取请求。
现在,这也解决了第二个问题,即设置“selected”元素,你想使用d3的selection.property()函数,该函数是为了设置dom元素上的非属性属性而设计的。另外,您想使用“checked”,而不是“selected”作为要设置的属性:
.property("checked", function(d, i) {
return (i===j);
});
看看这个 fiddle :http://jsfiddle.net/reblace/YyuY4/9/
关于d3.js - D3 中的单选按钮 : how to align text correctly and select a default?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19302318/