猿问

检查是否使用jQuery选择了选项,如果未选择默认选项

使用jQuery,如何检查选择菜单中是否有选项,如果没有,则将其中一个选项分配为选中状态。


(选择是通过我刚刚继承的应用程序中的PH


缥缈止盈
浏览 522回答 3
3回答

12345678_0001

虽然我不确定您到底想完成什么,但是这段代码对我有用。<select id="mySelect" multiple="multiple">&nbsp; <option value="1">First</option>&nbsp; <option value="2">Second</option>&nbsp; <option value="3">Third</option>&nbsp; <option value="4">Fourth</option></select><script type="text/javascript">&nbsp;$(document).ready(function() {&nbsp; if (!$("#mySelect option:selected").length) {&nbsp; &nbsp; $("#mySelect option[value='3']").attr('selected', 'selected');&nbsp; }});</script>

千巷猫影

无需为此使用jQuery:var foo = document.getElementById('yourSelect');if (foo){&nbsp; &nbsp;if (foo.selectedIndex != null)&nbsp; &nbsp;{&nbsp; &nbsp; &nbsp; &nbsp;foo.selectedIndex = 0;&nbsp; &nbsp;}&nbsp;}分享编辑

慕神8447489

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