<select size="2">
<option selected="selected">Input your option</option>
<option>Input your option</option>
</select>

使用jQuery优雅地取消选项的最佳方法是什么?


当前回答

通常当我使用选择菜单时,每个选项都有一个与之相关的值。 例如

<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

现在,这并没有从选项中删除选中的属性,但我真正想要的是值。

其他回答

$("option:selected").attr("selected", false);

另一种简单的方法:

$ (" # selectedID”)[0 - 9]。选择= -1

哦,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

为了向你们展示这个有多快,基准测试

一个快速谷歌发现这篇文章,描述了如何在IE中为单个和多个选择列表做你想做的事情。解决方案似乎也很优雅:

$('#clickme').click(function() {
        $('#selectmenu option').attr('selected', false);

}); 

通常当我使用选择菜单时,每个选项都有一个与之相关的值。 例如

<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

现在,这并没有从选项中删除选中的属性,但我真正想要的是值。