【问题标题】:Get "data-something" from an <option> tag contained in <select>从 <select> 中包含的 <option> 标记中获取“data-something”
【发布时间】:2013-07-17 23:33:45
【问题描述】:

我有这个 HTML

<select id="something">
    <option value="1" data-something="true">Something True</option>
    <option value="2" data-something-else="false">Something Else False</option>
</select>

还有我试图从data-*属性中获取值的这个jQuery sn-p:

$(document).ready(function() {
    $('body').on('change', 'select#something', function() {
        console.log( $(this).data('something') ); // undefined always
        console.log( $(this).data('something-else') ); // undefined always too
    });
});

如何用jQuery获取data-*属性值?

【问题讨论】:

    标签: javascript jquery html custom-data-attribute jquery-data


    【解决方案1】:

    this 是选择元素。

    console.log($(this).find(":selected").data("something"))
    

    【讨论】:

    • 你太快了!您必须等待 15 分钟,这样我才能接受这个答案!谢谢!
    • 只是好奇,对jq不强; $(this).find(":selected") 和 $(":selected", this) 一样吗?
    • @dandavis 在功能上是一样的
    猜你喜欢
    • 2021-12-15
    • 2013-10-22
    • 2022-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-20
    • 2010-12-21
    相关资源
    最近更新 更多