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

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


当前回答

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

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

其他回答

这个问题已经问了一段时间了,我还没有在旧的浏览器上测试过,但在我看来,一个更简单的答案是

$("#selectID").val([]);

.val()也适用于select http://api.jquery.com/val/

简单的方法

(“select”美元)。瓦尔(”)

我只是在select本身上使用了这个,它做到了。

我使用的是jQuery 1.7.1。

这里有很多答案,但不幸的是,所有的答案都很旧,因此依赖于attr/removeAttr,这真的不是正确的方法。

@coffeeyesplease正确地提到了一个好的、跨浏览器的解决方案

$("select").val([]);

另一个好的跨浏览器解决方案是

// Note the use of .prop instead of .attr
$("select option").prop("selected", false);

你可以看到它在运行自检。在IE 7/8/9, FF 11, Chrome 19上测试。

另一种简单的方法:

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

使用removeAttr……

$("option:selected").removeAttr("selected");

或道具

$("option:selected").prop("selected", false)