我一直在寻找一种从下拉列表选项中获取id
的方法,当它被选中时。我发现了以下内容:
Get selected text from a drop-down list (select box) using jQuery
并试图将接受的答案改为:
$("#yourdropdownid option:selected").id;
但是当我alert()
时,它给了我“未定义”。有没有办法使用JQuery获取id?
答案 0 :(得分:5)
因为$("#yourdropdownid option:selected")
返回一个没有id
属性的jQuery对象,所以可以使用.attr()来获取元素的id
$("#yourdropdownid option:selected").attr('id');
答案 1 :(得分:2)
使用.attr()
或.prop()
$("#yourdropdownid option:selected").prop('id')
或
$("#yourdropdownid option:selected").attr('id')
如果你想使用纯JavaScript,那么:
var obj=document.getElementById("myId").options[document.getElementById("myId").selectedIndex];
alert(obj.id);
不要将jquery对象与js属性混合,如$("#yourdropdownid option:selected").id
。