我目前使用以下javascript从下面的HTML中选择一个元素。如何同时选择多个值?
脚本:
//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>
...
答案 0 :(得分: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');
}
}
答案 1 :(得分:0)
如果想通过相同的选择框选择多个值,请尝试使用
<select multiple="multiple">
如果想使用javascript选择多个元素,请尝试使用逗号分隔元素。
document.querySelectorAll('select#selectEleId, #eleId2');
希望这会有所帮助......