3 回答

TA貢獻(xiàn)1802條經(jīng)驗(yàn) 獲得超5個(gè)贊
雖然我不確定您到底想完成什么,但是這段代碼對(duì)我有用。
<select id="mySelect" multiple="multiple">
<option value="1">First</option>
<option value="2">Second</option>
<option value="3">Third</option>
<option value="4">Fourth</option>
</select>
<script type="text/javascript">
$(document).ready(function() {
if (!$("#mySelect option:selected").length) {
$("#mySelect option[value='3']").attr('selected', 'selected');
}
});
</script>

TA貢獻(xiàn)1829條經(jīng)驗(yàn) 獲得超7個(gè)贊
無需為此使用jQuery:
var foo = document.getElementById('yourSelect');
if (foo)
{
if (foo.selectedIndex != null)
{
foo.selectedIndex = 0;
}
}
分享編輯

TA貢獻(xiàn)1780條經(jīng)驗(yàn) 獲得超1個(gè)贊
這個(gè)問題很老,并且有很多觀點(diǎn),所以我只想提出一些可以肯定的東西。
要檢查選擇元素是否有任何選定項(xiàng):
if ($('#mySelect option:selected').length > 0) { alert('has a selected item'); }
或檢查選擇項(xiàng)是否未選擇:
if ($('#mySelect option:selected').length == 0) { alert('nothing selected'); }
或者您是否處于某種循環(huán)中,并且想要檢查是否選擇了當(dāng)前元素:
$('#mySelect option').each(function() {
if ($(this).is(':selected')) { .. }
});
檢查循環(huán)中是否未選擇元素:
$('#mySelect option').each(function() {
if ($(this).not(':selected')) { .. }
});
這些是執(zhí)行此操作的一些方法。jQuery具有完成同一件事的許多不同方式,因此您通常只需選擇哪種方式似乎效率最高。
添加回答
舉報(bào)