javascript - 检查 HTML select 元素是否为空

标签 javascript d3.js

我在 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/

相关文章:

javascript - 如何允许iframe访问Element.prototype

javascript - 在 node.js 中使用数据库请求的结果

javascript - D3 多线图显示 2 条线而不是 3 条线

javascript - DC.js 使图表容器或 div 更宽以正确显示图例

javascript - 需要代码html5 slider ,显示值作为计算

javascript - 如何检查原型(prototype)函数是否不同

javascript - HTML 未读取 %0A

javascript - D3JS - 在散点图中显示圆形和三 Angular 形

javascript - d3.geoEquirectangular() 对 map 的渲染不一致

javascript - d3js - 如何为可以更新的多组元素绘制多折线图图表?