获取"data something“;从<选项>包含在<选择>

Get "data-something" from an <option> tag contained in <select>

本文关键字:lt gt 选项 选择 包含 quot data something 获取      更新时间:2023-09-26

我有这个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>

还有这个jQuery片段,我正试图用它从data-*属性中获取值:

$(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-*属性值

this是选择元素。

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