Javascript 使用jQuery选择一个选项? N M
在jQuery中,如何使id=m的选项“selected”呢?只需在选项上设置Javascript 使用jQuery选择一个选项? N M,javascript,jquery,Javascript,Jquery,在jQuery中,如何使id=m的选项“selected”呢?只需在选项上设置selected属性: <select> <option value="0" id="n">n</option> <option value="1" id="m">m</option> </select> 如果在执行此操作时还想取消选择其他选项,最简单的选项是: $("#m").attr("sele
selected
属性:
<select>
<option value="0" id="n">n</option>
<option value="1" id="m">m</option>
</select>
如果在执行此操作时还想取消选择其他选项,最简单的选项是:
$("#m").attr("selected", true);
但是,这不包括字段集的情况。要涵盖这些内容,请使用以下内容:
$("#m").attr("selected", true).siblings("option").removeAttr("selected");
为select中的每个选项添加id的方法不正确。如果我是你,我会喜欢下面的
$("#m").attr("selected", true).closest("select")
.find("option").removeAttr("selected");
改为在select元素上设置id:
$("#myselect option:eq(1)").attr("selected", "selected");
我同意@coder。对其代码的一个轻微更改是删除先前选择的条目。如果用户已经选择了一个选项,然后您想使用jquery将其更改为其他选项(除非您的选择框设置了属性“multiple”),则必须取消选择用户的选择选项
$(“#myselect option:eq(1)”).attr(“已选择”、“已选择”).slides(“选项”).removeAttr(“已选择”);
正如@cletus.所提到的,这在FF 8.0或Chrome 11.0中对我都不起作用(但是.attr('selected',true)确实起作用)@NickPerkins:The
select
元素没有任何selected
属性,因此,我认为您做错了的是,您试图在选项上使用val
,而不是选择
。
$("#myselect option:eq(1)").attr("selected", "selected");
<select id="TheDropDown">
<option value="0">n</option>
<option value="1">m</option>
</select>
$('#TheDropDown').val('1');
$("#m").addAttr('selected', true)
.siblings('option')
.removeAttr('selected');