如何从jQuery的select选项中获取属性? [英] How to get attribute from selected option of select in jQuery?
问题描述
我在HTML中有下一个选择框:
I have the next selectbox in HTML:
<select id="listbox-taskStatus" class="selectpicker">
<option status="0">In progress</option>
<option status="1">Not started</option>
<option status="2">Done</option>
<option status="3">Failed</option>
</select>
我想从所选期权中读取属性值。
I want to read the attribute value from selected option.
如果只是取值,那很简单:
If just to take the value, it's simple:
var value = $('#listbox-taskStatus').val();
但如果我想从所选期权中获取属性值,我该怎么办?
我知道, .attr()必须有所帮助,但当我尝试使用它时,我的结果不正确。
But what should I do, if I want to get the attribute value from selected option? I know, that .attr() must help, but when I tried to use it I've got the incorrect result.
我尝试了下一个:
var status = $('#listbox-taskStatus option').attr('status');
但是返回的值总是 0
尽管事实上我选择了不同的选项。
But the returned value is always 0
despite on fact I was selecting different option.
怎么了,怎么解决我的问题?
What's wrong, how to solve my problem?
推荐答案
使用:已选择选择器
var status = $('#listbox-taskStatus option:selected').attr('status');
但是,我建议您使用数据 -
前缀属性。然后你可以使用 .data()
However, I would recommend you to use data-
prefixed attribute. Then you can use .data()
var status = $('#listbox-taskStatus option:selected').data('status');
这篇关于如何从jQuery的select选项中获取属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!