有没有一种方法可以搜索选择表单元素中的所有选项,并将具有匹配值的选项指定为“选中”?
var xStat = "G";
var statOptions = {
"Points": "PTS",
"Goals": "G",
"Assists": "A",
"Penalty Minutes": "PIM"
};
// create the select element
var selectUI = d3.select("#horse").append("form").append("select");
// create the options
selectUI.selectAll("option").data(d3.keys(statOptions)).enter().append("option").text(function(d) {
return d;
});
// add values to the options
selectUI.selectAll("option").data(d3.values(statOptions)).attr("value", function(d) {
return d;
});
// create a func to check if the value of an option equals the xStat var
// if yes, set the attribute "selected" to "selected"
var checkOption = function(e, i, a) {
if (e[i]["value"] === xStat) {
return e[i].attr("selected", "selected");
}
};
// selectUI.selectAll("option").forEach(checkOption);
selectUI.selectAll("option").call(checkOption);
我在此处包括了我的非工作尝试: http://jsfiddle.net/sspboyd/LzrAC/2/
最佳答案
这似乎有效:
selectUI.property( "value", xStat );
我自己是新手,在同一个问题上摸索着。 如果这不是正确的方式,我很想知道什么是正确的。
关于javascript - 如何使用 D3(或只是 javascript)将表单选项设置为 "selected",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13097923/