2014-03-25 16 views
1

我目前使用以下javascript從下面的HTML中選擇一個元素。我怎樣才能同時選擇多個值?如何使用userscript選擇多個<option>值?

腳本:

//Select Forum 
var forumselector = document.querySelector('select#forumchoice'); 
forumselector.value = 326; 

HTML:

<select class="primary" id="forumchoice" name="forumchoice[]" multiple="multiple" tabindex="1" size="5">       
<option value="" class="" selected="selected">Search All Open Forums</option> 
<option value="subscribed" class="" >Search Subscribed Forums</option> 
<option value="130" class="d0" > The Community</option> 
<option value="327" class="d1" > General Support</option> 
<option value="326" class="d2" > Beginners Section</option> 
<option value="331" class="d2" > General Help</option> 
... 

回答

1

您可以使用document.querySelectorAll並通過節點列表迭代:

var forumselector = document.querySelectorAll('select#forumchoice option'); 

for (var i = 0; i < forumselector.length; i++) { 
    if (['327', '331'].indexOf(forumselector[i].value) != -1) { 
     forumselector[i].setAttribute('selected', 'selected'); 
    } 

} 

Demo

+0

效果很好,感謝:) – resurrectedstar

0

如果要選擇通過同一個選擇框多個值,那麼試試這個

<select multiple="multiple"> 

如果想選擇用javascript多個元素然後嘗試使用逗號分隔的元素。

document.querySelectorAll('select#selectEleId, #eleId2'); 

希望這有助於...