3 回答

TA贡献1802条经验 获得超5个赞
虽然我不确定您到底想完成什么,但是这段代码对我有用。
<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贡献1829条经验 获得超7个赞
无需为此使用jQuery:
var foo = document.getElementById('yourSelect');
if (foo)
{
if (foo.selectedIndex != null)
{
foo.selectedIndex = 0;
}
}
分享编辑

TA贡献1780条经验 获得超1个赞
这个问题很老,并且有很多观点,所以我只想提出一些可以肯定的东西。
要检查选择元素是否有任何选定项:
if ($('#mySelect option:selected').length > 0) { alert('has a selected item'); }
或检查选择项是否未选择:
if ($('#mySelect option:selected').length == 0) { alert('nothing selected'); }
或者您是否处于某种循环中,并且想要检查是否选择了当前元素:
$('#mySelect option').each(function() {
if ($(this).is(':selected')) { .. }
});
检查循环中是否未选择元素:
$('#mySelect option').each(function() {
if ($(this).not(':selected')) { .. }
});
这些是执行此操作的一些方法。jQuery具有完成同一件事的许多不同方式,因此您通常只需选择哪种方式似乎效率最高。
添加回答
举报