我在 HTML 中有以下选择元素:
<div id="myselect">
Results
<select></select>
</div>
我用数据库中的数据(如果有)填充它,然后我想检查它是否包含任何元素,所以我这样做:
var myselect = d3.select('#myselect select');
var r = myselect.datum();
if(r.option.length != 0) {
...
}
这里的问题是 myselect
是一个我知道只有一个元素的数组。我认为 datum()
是获取该值的方法,但这使得 r
为空。
最佳答案
您可以使用selection.empty()确定选择是否为空。
const isEmpty = d3.selectAll("div").empty();
对于你的特殊例子,你可能想要更多类似这样的东西。您要做的是检查选择是否为空,然后使用 selection.node() 从该选择中获取实际的 HTMLElement
.
var myselect = d3.select('#myselect select');
if (!myselect.empty()) {
var node = myselect.node();
var options = node.options;
if (options.length > 0) {
}
}
datum()
函数的使用方式有所不同,它将返回所选内容已绑定(bind)到的数据对象。例如,如果您这样做:
d3.selectAll("div")
.data(["A", "B", "C"])
.enter()
.append("div")
.attr("class", function(d) { return d; }); // will return a letter
// Go select a div and grab the data object it's bound to
// which will return the array item "B", but this could have
// equally been a complex object
d3.select("div.B").datum();
关于javascript - 检查 HTML select 元素是否为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41138188/