javascript 使用 jQuery 从下拉列表(选择框)中获取选定的 id

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30159995/
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-10-28 11:50:10  来源:igfitidea点击:

Get selected id from drop-down list (select box) using jQuery

javascriptjquery

提问by Julian Avar

I have been searching for a way to get the idfrom a drop-down list option, when it is selected. I have found the following: Get selected text from a drop-down list (select box) using jQuery
And tried to change the accepted answer to:

我一直在寻找一种id从下拉列表选项中获取 的方法,当它被选中时。我发现了以下内容: 使用 jQuery 从下拉列表(选择框)中获取选定的文本
并尝试将接受的答案更改为:

$("#yourdropdownid option:selected").id;

But when I alert()it, it gives me "undefined". Is there a way to get the id using JQuery?

但是当我alert()它时,它给了我“未定义”。有没有办法使用 JQuery 获取 id?

回答by Arun P Johny

Because $("#yourdropdownid option:selected")returns a jQuery object which does not have the idproperty so, you can use .attr() to get id of the element

因为$("#yourdropdownid option:selected")返回一个没有id属性的 jQuery 对象,所以你可以使用 .attr() 来获取元素的 id

$("#yourdropdownid option:selected").attr('id');

回答by Brijesh Bhatt

Get the id using .attr()or .prop():

使用.attr()或获取ID .prop()

$("#yourdropdownid option:selected").prop('id')

or

或者

$("#yourdropdownid option:selected").attr('id')

and if you want to use pure javascript then:

如果你想使用纯 javascript,那么:

var obj=document.getElementById("myId").options[document.getElementById("myId").selectedIndex];
alert(obj.id);

Don't mix the jquery object with js property like $("#yourdropdownid option:selected").id.

不要将 jquery 对象与 js 属性(如$("#yourdropdownid option:selected").id.