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
jQuery - select tag - get attribute of the selected element
提问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 :selected
filter.
您可以只使用: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/