jQuery - 选择标签 - 获取被选元素的属性

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

jQuery - select tag - get attribute of the selected element

jqueryselectattributes

提问by user398341

Is there a way of getting the attribute - such as 'rel' from the selected option of the 'select' tag - i.e.?

有没有办法从'select'标签的选定选项中获取属性 - 例如'rel' - 即?

<select name="menu" id="menu">
    <option value="1" rel="123">Option 1</option>
    <option value="2" rel="124">Option 2</option>
</select>

Any idea?

任何的想法?

回答by JohnP

You can just use the :selectedfilter.

您可以只使用:selected过滤器。

Here's a fiddle : http://jsfiddle.net/jomanlk/ECAea/

这是一个小提琴:http: //jsfiddle.net/jomanlk/ECAea/

$('#menu').change(function(){
    alert($(this).find('option:selected').attr('rel'));
});

回答by Gabriele Petrioli

with jQuery

使用 jQuery

$('#menu option:selected').attr('rel');

with javascript

使用 JavaScript

var sel = document.getElementById('menu');
var option = sel.options[sel.selectedIndex];
var rel = option.getAttribute('rel');

demo with both versions at http://jsfiddle.net/gaby/WLFmv/

两个版本的演示在http://jsfiddle.net/gaby/WLFmv/

回答by verdesmarald

You can use .attr("attributeName")to get the value of attributes. See .attr().

您可以使用.attr("attributeName")来获取属性的值。见.attr()

To find the selected option you can use $('#menu option[selected=true]')or similar.

要查找您可以使用$('#menu option[selected=true]')或类似的选定选项。