Javascript 使用JS在已填充的select标记中选择一个选项
假设我有一个Javascript 使用JS在已填充的select标记中选择一个选项,javascript,Javascript,假设我有一个select标记,如下所示: <select name='selectBox' id='selectBox'> <option value='1'>one</option> <option value='2'>two</option> <option value='3'>three</option> <option value='4'>four</op
select
标记,如下所示:
<select name='selectBox' id='selectBox'>
<option value='1'>one</option>
<option value='2'>two</option>
<option value='3'>three</option>
<option value='4'>four</option>
<option value='5'>five</option>
</select>
但我想在选项的text
上选择。我是这方面的初学者,任何帮助都将不胜感激
谢谢。您必须获得选项索引:
var options = $("#selectBox > option");
$('#selectBox').prop('selectedIndex', options.index(":contains(three)"));
您必须获得选项索引:
var options = $("#selectBox > option");
$('#selectBox').prop('selectedIndex', options.index(":contains(three)"));
试试这个:-
var text = "five"
$(document).ready(function() {
$('#selectBox option').each(function(index){
if($(this).text() === text){
$('#selectBox').prop('selectedIndex', index);
}
})
});
试试这个:-
var text = "five"
$(document).ready(function() {
$('#selectBox option').each(function(index){
if($(this).text() === text){
$('#selectBox').prop('selectedIndex', index);
}
})
});
您可以使用
each()
尝试以下方法:
让selectVal='three';
$(“#选择框选项”)。每个(函数(){
if($(this).text()==selectVal)
$('selectBox').prop('selectedIndex',2);
});代码>
一
二
三
四
五
您可以使用each()尝试以下方法。
:
让selectVal='three';
$(“#选择框选项”)。每个(函数(){
if($(this).text()==selectVal)
$('selectBox').prop('selectedIndex',2);
});代码>
一
二
三
四
五
这是纯香草js
var element = document.getElementById(id);
element.value = valueToSelect;
这是纯香草js
var element = document.getElementById(id);
element.value = valueToSelect;
可能的重复可能的重复可能的重复可能的重复