jQuery - 按元素 id 设置选择索引
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14317962/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery - set select index by elements id
提问by Marcin Bobowski
<select id="mySelect">
<option id="sel01" value="some value">some value</option>
<option id="sel02" value="some other value">some other value</option>
<option id="sel03" value="maybe me">maybe me</option>
<option id="sel04" value="and another one">and another one</option>
</select>
I would like to select an option with use of jQuery, but not by value:
我想选择一个使用 jQuery 的选项,但不是按值:
$("#mySelect").val(1);
but by elements id.
但通过元素 id。
Thanks for an answer.
谢谢你的回答。
回答by undefined
You can use prop
method.
您可以使用prop
方法。
var id = 'sel02';
$('#mySelect option').filter(function(){
return this.id === id
}).prop('selected', true);
or:
或者:
$('#' + id).prop('selected', true);
Or if you want to select an option based on it's index, you can use eq
method:
或者如果你想根据它的索引选择一个选项,你可以使用eq
方法:
$('#mySelect option').eq(1).prop('selected', true);
回答by THE ONLY ONE
var id= "sel01";
$('#selectid option').each(function(){
if($(this).attr('id') == id){
$(this).attr('selected',true);
}
});
回答by Konstantin Dinev
You can retrieve the element value using the ID and use the value for the jQuery val()
.
您可以使用 ID 检索元素值并将该值用于 jQuery val()
。
var elementId = 'sel01';
$("#mySelect").val($('#' + elementId).val());
回答by Jai
If you want to select the option:
如果要选择该选项:
$('#mySelect option#sel02').prop('selected',true);
if you want to get the selected option id's value:
如果要获取所选选项 ID 的值:
$('#mySelect option#sel02').val();
回答by Rohit416
回答by AndreSites
I don't know the context but this worked for me when I needed to get data from json and make the option of that specific combo box selected:
我不知道上下文,但是当我需要从 json 获取数据并选择该特定组合框的选项时,这对我有用:
$("#mySelect option[id='" + someVariable + "']").attr('selected', 'selected');
回答by AlienHoboken
Like this. Just change the number in eq(0)
像这样。只需更改 eq(0) 中的数字
$("#mySelect").val($("#mySelect").children().eq(0).val());