如何从jQuery中select的选定选项中获取属性? [英] How to get attribute from selected option of select in jQuery?

查看:20
本文介绍了如何从jQuery中select的选定选项中获取属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 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?

推荐答案

使用 :selected选择器

var status = $('#listbox-taskStatus option:selected').attr('status');

但是,我建议您使用 data- 前缀属性.然后你可以使用 .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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆