我怎样才能使用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)
你不需要"取消选择".当您选择另一个时,会自动发生.
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/
您可以使用
$('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)
| 归档时间: |
|
| 查看次数: |
155085 次 |
| 最近记录: |