<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优雅地取消选项的最佳方法是什么?
当前回答
$(option).removeAttr('selected') //replace 'option' with selected option's selector
其他回答
这个代码适用于我。
$("option:selected").prop("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
现在,这并没有从选项中删除选中的属性,但我真正想要的是值。
$("#select_id option:selected").prop("selected", false);
另一种简单的方法:
$ (" # selectedID”)[0 - 9]。选择= -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上测试。