下面的代碼假設將下拉列表與div內容匹配。如果找到「Pineapple」,則選擇此選項。我似乎無法找到錯誤。基於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,似乎沒有辦法。
因爲不僅使用jQuery? – alditis
jQuery one liner'$(「#mySelect」)。val($('#myContent')。text());' – Musa
修復輸入錯誤很好http://jsfiddle.net/gaby/4FWAA/ –