jQuery使用Next设置选定的选项

42 jquery html-select

我怎样才能使用jQuery将已选择项目的"下一个"项设置为"已选中".

例如,如果我有:

<select>
<option value="1" >Number 1</option>
<option value="2" selected="selected">Number 2</option>
<option value="3" >Number 3</option>
<option value="4" >Number 4</option>
</select>
Run Code Online (Sandbox Code Playgroud)

我们可以看到选择了"Number 2",并且使用jQuery,我想将"Number 3"设置为选中,并从"Number 2"中删除所选的"属性".我假设我需要使用下一个选择器,但我不太确定如何实现.

Gto*_*heB 115

更新:

从jQuery 1.6+开始,你应该使用prop()而不是attr()在这种情况下.

在特定情况下,属性和属性之间的差异可能很重要.在jQuery 1.6之前,.attr()方法有时在检索某些属性时会考虑属性值,这可能会导致行为不一致.从jQuery 1.6开始,.prop()方法提供了一种显式检索属性值的方法,而.attr()则检索属性.

var theValue = "whatever";
$("#selectID").val( theValue ).prop('selected',true);
Run Code Online (Sandbox Code Playgroud)


原答案:

如果要按选项的值选择,请选择其位置的REGARDLESS(此示例假定您具有选择的ID):

var theValue = "whatever";
$("#selectID").val( theValue ).attr('selected',true);
Run Code Online (Sandbox Code Playgroud)

你不需要"取消选择".当您选择另一个时,会自动发生.

  • @understack.是.是的,它会的.今天早上我们在这个问题上挣扎.接得好.+1我们最终使用:`$("selectID").find("option [value ='"+ theValue +"']").attr("selected","selected")`这个工作正常 (18认同)
  • 不会.attr('selected',true)将所选属性添加到select元素而不是option. (6认同)
  • 一年后是的,但我刚刚遇到这个代码.你假设当你选择另一个时自动取消选择该项目,你犯了一个小错误.当选项列表是多选时,情况并非如此.我只是想指出这一点,万一有人预料到这种行为并且因为它没有像宣传的那样工作而感到沮丧. (4认同)

DLS*_*DLS 60

$('option:selected', 'select').removeAttr('selected').next('option').attr('selected', 'selected');
Run Code Online (Sandbox Code Playgroud)

在这里查看工作代码 http://jsbin.com/ipewe/edit


小智 17

从版本1.6.1开始,建议将方法prop用于布尔属性/属性,例如selected,readonly,enabled,...

var theValue = "whatever";
$("#selectID").val( theValue ).prop('selected',true);
Run Code Online (Sandbox Code Playgroud)

有关详细信息,请参阅http://blog.jquery.com/2011/05/12/jquery-1-6-1-released/


Kob*_*obi 6

您可以使用

$('option:selected').next('option')
Run Code Online (Sandbox Code Playgroud)

要么

$('option:selected + option')
Run Code Online (Sandbox Code Playgroud)

并设置值:

var nextVal = $('option:selected + option').val();
$('select').val(nextVal);
Run Code Online (Sandbox Code Playgroud)