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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 13:27:21  来源:igfitidea点击:

jQuery - set select index by elements id

jqueryselectjquery-selectors

提问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 propmethod.

您可以使用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 eqmethod:

或者如果你想根据它的索引选择一个选项,你可以使用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

Try this syntax,

试试这个语法,

$('select option:selected').attr('id');

check here, it will select the option based on the text value.

检查此处,它将根据文本值选择选项。

回答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());