2016-12-14 36 views
-2

,我有以下的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爲空。

+4

嘗試F12和執行console.log(myselect) – mplungjan

回答

2

您可以使用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()功能用於不同的,這將返回的數據對象,所述選擇已經綁定。例如,如果你做的事:

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(); 
1

看起來您正在嘗試爲您的<select>獲取原始HTMLSelectElement。嘗試使用.node()

var myselect = d3.select('#myselect select'); 
var r = myselect.node(); 
if (r.options.length != 0) { // options, not option? 
    ... 
} 
-1

你可以簡單地檢查options長度select標籤的一個簡單的JavaScript:

var myselect = document.getElementById('myselect'); 
if(myselect.getElementsByTagName('select')[0].options.length!=0){ 
    //your code here 
}