<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优雅地取消选项的最佳方法是什么?
当前回答
到目前为止,答案只适用于IE6/7中的多项选择;对于更常见的非多选择,您需要使用:
$("#selectID").attr('selectedIndex', '-1');
这在flyfishr64链接的帖子中有解释。如果你仔细看,你会发现有两种情况——多/非多。没有什么能阻止你为了一个完整的解决方案而改变两者:
$("#selectID").attr('selectedIndex', '-1').find("option:selected").removeAttr("selected");
其他回答
简单的方法
(“select”美元)。瓦尔(”)
我只是在select本身上使用了这个,它做到了。
我使用的是jQuery 1.7.1。
到目前为止,答案只适用于IE6/7中的多项选择;对于更常见的非多选择,您需要使用:
$("#selectID").attr('selectedIndex', '-1');
这在flyfishr64链接的帖子中有解释。如果你仔细看,你会发现有两种情况——多/非多。没有什么能阻止你为了一个完整的解决方案而改变两者:
$("#selectID").attr('selectedIndex', '-1').find("option:selected").removeAttr("selected");
一个快速谷歌发现这篇文章,描述了如何在IE中为单个和多个选择列表做你想做的事情。解决方案似乎也很优雅:
$('#clickme').click(function() {
$('#selectmenu option').attr('selected', false);
});
$("option:selected").attr("selected", false);
哦,jquery。
既然还没有原生的javascript方法,我觉得有必要提供一个。
var select = document.querySelector('select'); //hopefully you'll use a better selector query
select.selectedIndex = 0; // or -1, 0 sets it to first option, -1 selects no options
为了向你们展示这个有多快,基准测试