2014-04-22 123 views
5
<select id="comboBox"> 
    <option id="1">One</option> 
    <option id="2">Two</option> 
    <option id="3">Three</option> 
    <option id="4">Four</option> 
</select> 

我想選擇ID爲3的選項。有什麼辦法如何做到沒有循環?我期待這樣的事情如何通過其ID設置select元素的選定選項?

$("#comboBox").val("3"); 

但用ID而不是價值。 (因此,我的意思是訪問該選擇,因爲組合框的構件,而不是通過像document.getElementById('3');選擇器)

+0

'的document.getElementById( '3') ;'? – Matt

+0

我打算通過'comboBox'元素以某種方式設置它。 – juice

+0

請更改您的問題,以便解釋您想要發生的事情。 –

回答

10
<script type="text/javascript"> 
    document.getElementById("3").selected=true; 
</script> 

<script type="text/javascript"> 
    document.getElementById("comboBox").options[2].selected=true; 
</script> 

<script type="text/javascript"> 
    document.getElementById("comboBox").selectedIndex=2; 
</script> 

<script type="text/javascript"> 
    document.getElementById("comboBox").options.namedItem("3").selected=true; 
</script> 

最後一個請看https://developer.mozilla.org/en/docs/Web/API/HTMLSelectElement#namedItem()http://www.w3schools.com/jsref/coll_select_options.asp

你可以跳過參考選項較短document.getElementById("comboBox").namedItem("3").selected=true;

2

嘗試document.querySelector('option[id="3"]').setAttribute('selected', true)document.querySelector('#comboBox > option[id="3"]').selected=true

JsFiddle

0

這爲我工作:

$("#2").attr({"selected": true}); 

注意我正在使用JQuery選擇器和.attr函數。

0

你可以試試這個,如果你的ID是在同一順序

document.getElementById("comboBox").selectedIndex = 2; 

Demo

0

selectedIndex是HTMLSelectElement的屬性,你可以使用index屬性來獲取它的索引,所以你可以做以下:

document.getElementById("comboBox").selectedIndex = document.getElementById('3').index; 

更新時間:Demo

更新的按鈕單擊事件選項:按遞減順序上按鈕的單擊事件New Demo

更新選項:Another Demo

+0

這不行,真的。什麼是'document.getElementById('3')。index'? – KooiInc

+0

它應該工作,** Demo **也在工作。 'document.getElementById('3')。index'用於獲取具有3'id'的'option'的索引。我已經更新了我的答案 – Manwal

+0

我站得更正了。假設在較早的版本中,小提琴腳本是在html-header中的。 'document.getElementById('3')。index'是一個現有的屬性,據說是因爲它是一個'option',很有趣。 – KooiInc

相關問題