使用jQuery获取所选选项id
我尝试使用jQuery根据所选选项发出ajax请求 是否有一种使用jQuery检索所选选项id(例如“id2”)的简单方法使用jQuery获取所选选项id,jquery,dom,jquery-selectors,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").chan
<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
});
选择1
选择2
$(“#我的选择”).change(函数(){
//使用所选选项的id执行某些操作
});
您可以使用,如下所示:
$("#my_select").change(function() {
var id = $(this).children(":selected").attr("id");
});
var id=$(this).find('option:selected').attr('id')代码>
然后使用selectedIndex
我重新编辑了我的答案。。。因为selectedIndex不是一个很好的变量来举例…最简单的方法是var id=$(this.val();从事件内部,如on change。2此处的注释,他已经在事件处理程序中具有带有this
的DOM元素,无需再次执行查找…并且可能希望选择另一个变量名,selectedIndex
在此处尤其不准确:)是。。。很抱歉我很着急。。。选择的索引变量在手。。。他当然不必再通过考试了。。如果我选择了这个选项,我会告诉你,因为它不需要.change函数。我如何在纯javascript中应用你的解决方案?这将返回所选选项的值,而不是ID(OP请求的ID)。
$('#my_select option:selected').attr('id');
$('#my_select option:selected').attr('id');