jquery 查找选择选项属性
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6208582/
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 find select options attributes
提问by coffeemonitor
I know how to get the attributes of an element, using jquery. But I'm not sure how to do it with the actual options in a select field.
我知道如何使用 jquery 获取元素的属性。但我不确定如何使用选择字段中的实际选项来实现。
<select referenceID="55" name="test" id="test">
<option value="1">first option</option>
<option value="2">second option</option>
<option value="3">third option</option>
</select>
To get the referenceID I would just do this:
要获得referenceID,我会这样做:
$("#test").attr("referenceID");
And when I want to get the value:
当我想获得价值时:
$("#test").val();
But I want to get a little more interesting. I want to put some specific info into each option:
但我想变得更有趣。我想在每个选项中加入一些特定的信息:
<select name="test" id="test">
<option value="1" title="something here"*>first option</option>
<option value="2" title="something else here">second option</option>
<option value="3" title="another thing here">third option</option>
</select>
Is it possible to grab an attribute within the options tags?
是否可以在选项标签中获取属性?
I intend to have an onselect function that reads the title tag, and does helps me with some other things.
我打算有一个 onselect 函数来读取标题标签,并帮助我做一些其他的事情。
回答by lonesomeday
Presuming you want to find the title
attribute of the selected option...
假设您要查找title
所选选项的属性...
$('#test option:selected').attr('title');
That is, find the descendant element of #test
that is (a) an option element and (b) is selected.
也就是说,找到它的后代元素#test
是 (a) 一个选项元素和 (b)被选中。
If you already have a selection containing #test
, you can do this with find
:
如果您已经有一个包含 的选择#test
,您可以使用find
:
$('#test').find('option:selected').attr('title');
回答by samsonasik
if you're using onchange, you can use like the following :
如果你使用 onchange,你可以使用如下:
$("#test").change(function(){
var title = $(this).find('option:selected').attr('title');
});
回答by Code Maverick
Does this not work?
这不起作用吗?
$("#test").change(function() {
var title = $(this).attr("title");
});