使用 jQuery 获取选定的选项 ID
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2888446/
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
Get the selected option id with jQuery
提问by botmsh
I'm trying to use jQuery to make an ajax request based on a selected option.
我正在尝试使用 jQuery 根据所选选项发出 ajax 请求。
Is there a simple way to retrieve the selected option id(e.g. "id2") using jQuery?
有没有一种简单的方法可以使用 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
});
回答by Nick Craver
You can get it using the :selected
selector, like this:
您可以使用:selected
选择器获取它,如下所示:
$("#my_select").change(function() {
var id = $(this).children(":selected").attr("id");
});
回答by Mihai Iorga
var id = $(this).find('option:selected').attr('id');
then you do whatever you want with selectedIndex
然后你可以随心所欲 selectedIndex
I've reedited my answer ... since selectedIndex isn't a good variable to give example...
我已经重新编辑了我的答案......因为 selectedIndex 不是一个很好的变量来举例......
回答by wild_nothing
$('#my_select option:selected').attr('id');
回答by jk121960
Th easiest way to this is var id = $(this).val(); from inside an event like on change.
最简单的方法是 var id = $(this).val(); 从一个事件内部,比如变化。