使用jQuery获取所选的选项ID

ISB*_*SBL 75 jquery dom jquery-selectors

我正在尝试使用jQuery根据选定的选项发出ajax请求.

有没有一种简单的方法来使用jQuery 检索所选的选项ID(例如"id2")?

<select id="my_select">
   <option value="o1" id="id1">Option1</option>
   <option value="o2" id="id2">Option2</option>
</select>


$("#my_select").change(function() {
    //do something with the id of the selected option
});
Run Code Online (Sandbox Code Playgroud)

Nic*_*ver 202

您可以使用:selected选择器获取它,如下所示:

$("#my_select").change(function() {
  var id = $(this).children(":selected").attr("id");
});
Run Code Online (Sandbox Code Playgroud)


Mih*_*rga 22

var id = $(this).find('option:selected').attr('id');

然后你做任何你想做的事 selectedIndex

我已经重新考虑了我的答案......因为selectedIndex不是一个很好的变量来举例...


wil*_*ing 17

$('#my_select option:selected').attr('id');
Run Code Online (Sandbox Code Playgroud)


jk1*_*960 6

最简单的方法是 var id = $(this).val(); 从一个事件内部,比如变化。