<select size="2">
<option selected="selected">Input your option</option>
<option>Input your option</option>
</select>
使用jQuery优雅地取消选项的最佳方法是什么?
<select size="2">
<option selected="selected">Input your option</option>
<option>Input your option</option>
</select>
使用jQuery优雅地取消选项的最佳方法是什么?
当前回答
在你的选择中设置一个id,像这样: <select id="foo" size="2">
然后你可以使用: $ (" # foo”)。道具(“selectedIndex”,0).change ();
其他回答
到目前为止,答案只适用于IE6/7中的多项选择;对于更常见的非多选择,您需要使用:
$("#selectID").attr('selectedIndex', '-1');
这在flyfishr64链接的帖子中有解释。如果你仔细看,你会发现有两种情况——多/非多。没有什么能阻止你为了一个完整的解决方案而改变两者:
$("#selectID").attr('selectedIndex', '-1').find("option:selected").removeAttr("selected");
这个问题已经问了一段时间了,我还没有在旧的浏览器上测试过,但在我看来,一个更简单的答案是
$("#selectID").val([]);
.val()也适用于select http://api.jquery.com/val/
$(option).removeAttr('selected') //replace 'option' with selected option's selector
通常当我使用选择菜单时,每个选项都有一个与之相关的值。 例如
<select id="nfl">
<option value="Bears Still...">Chicago Bears</option>
<option selected="selected" value="Go Pack">Green Bay Packers</option>
</select>
console.log($('#nfl').val()) logs "Go Pack" to the console
Set the value to an empty string $('#nfl').val("")
console.log($('#nfl').val()) logs "" to the console
现在,这并没有从选项中删除选中的属性,但我真正想要的是值。
$("#selectID option:selected").each(function(){
$(this).removeAttr("selected");
});
这将遍历每个项目,只取消选中的项目