下面的代码假设将下拉列表与 div 内容匹配。如果找到“菠萝”,则选择此选项。我似乎找不到错误。
<head>
<script>
function displayResult(){
var myObject=document.getElementById("mySelect");
var myValue = $('#myContent').text();
for(var i=0; i<myObject.length; i++){
if(myObject.options[i].text == myValue){
myObject.options[i].selected = true;
(also tried - myObject.options[i].selectedIndex = i;)
break;
}
}
}
</script>
</head>
<body>
<div id="myContent">Pineapple</div>
<form>
Select your favorite fruit:
<select id="mySelect" size="4">
<option>Apple</option>
<option>Orange</option>
<option>Pineapple</option>
<option>Banana</option>
</select>
</form>
<button type="button" onclick="displayResult()">Highlight Pineapple Option</button>
</body>
笔记:
我希望突出显示该选项。缺少右括号是一个错字,已更正。尝试过 .selectedIndex=i,似乎没有奏效。