2012-11-02 157 views
1

我認爲我的選擇/選項標籤有問題...我無法訪問選定的選項。選擇選項 - 無法獲取選項

這裏的HTML部分:

<select id="filter"> 
    <option value="value1" selected="selected" data-path="property1">option1</option> 
    <option value="value2" data-path="property2">option2</option> 
</select> 

我試着這樣說:

var property_filter = document.getElementById('filter'); 

而且在調試時,在控制檯上,這是我的嘗試:

input: property_filter.options 
output: [<option value=​"value1" selected=​"selected" data-path=​"property1">​option1</option>​,<option value=​"value2" data-path=​"property2">​option2​</option>​] 

所以它抓住了正確的選擇標籤...但仍有一些錯誤:

input: property_filter.selectedIndex 
output: -1 

同樣,當我使用JQuery選擇器來找到這個,我沒有得到我想要的。

input: $('#filter').find('option') 
output: [<option value=​"value1" selected=​"selected" data-path=​"property1">​option1​</option>​, <option value=​"value2" data-path=​"property2">​option2​</option>​] 

input: $('#filter').find('option:selected') 
output: [] 

我一定在做錯事情......這也是一件很簡單的事情。我也嘗試使用'選擇',而不是'選擇='選擇'',但我得到了同樣的結果。

我在OS 10.6.8上順便使用了Chrome,並且在Backbone View & QUnit測試的環境下(但它沒關係,對不對?)。此外,此代碼在QUnit之外工作。

+0

在JavaScript中,其'selectedIndex',在jQuery中它是':selected'。 – j08691

+0

嘗試.hasAttribute(「selected」);檢查它是否被設置,也許你正在修改它 – RyanS

+0

http://jsfiddle.net/mqefD/1/看起來不錯。 – jAndy

回答

0

啊......對不起。我發現爲什麼事情不起作用。就像彼得威爾金森說的那樣,這是我引入的一個錯誤。

在我嘗試獲取索引之前,我將索引設置爲2,(noob wrong !!),它將索引設置爲出界索引。這就是爲什麼我一直以-1作爲索引。

JQuery或者selectedIndex或者我嘗試過的任何方法都沒有問題+我應該進一步調試。

0

嘗試

console.log($(this).find('#filter option:selected'));