javascript 如何在选择中返回选项元素的数据属性?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12844618/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 17:14:36  来源:igfitidea点击:

how to return the data attribute of an option element in select?

javascriptjquery

提问by styler

Im trying to log out the data attribute i've attached to each option in my select box but with no success, am I correct using .on('change'... or what should I be doing to achieve this?

我试图注销我在选择框中附加到每个选项的数据属性,但没有成功,我是否正确使用 .on('change'... 或者我应该怎么做才能实现这一目标?

JS

JS

$('select').children().on('change', function(e){
    console.log( $(this).data('id') );
    e.preventDefault();
});

HTML

HTML

<select>
<option value="1" data-id="option1">wgwg</option>
<option value="1" data-id="option2">wgwerg</option>
<option value="1" data-id="option3">wgwg</option>
<option value="1" data-id="option4">wgr</option>
</select>?

回答by James Montagne

A change event on optiondoesn't really make sense as the optionis not changing. The event should be on the select.

更改事件option并没有真正意义,因为option没有改变。事件应该在select.

$('select').on('change', function(e){ 
    console.log( $(this).find("option:selected").data('id') ); 
    e.preventDefault(); 
}); 

回答by Adil

Try this,

试试这个,

Live Demo

现场演示

$('select').on('change', function(e){
    console.log( $('option:selected', this).data('id'));
    e.preventDefault();
});

回答by Arthur Araújo

You can it with Vanilla Javascript:

您可以使用Vanilla Javascript

console.log(this.querySelector(':checked').getAttribute('data-id'))

回答by Sushanth --

You seem to assign the event to the children of select which is wrong.. You need to assign the event to the select directly..

您似乎将事件分配给 select 的子项,这是错误的.. 您需要将事件直接分配给 select ..

Also thisdoes not have the data attribute. It is the option that is selected.. So change your code to this

this没有data属性。它是option that is selected.. 所以把你的代码改成这个

Try this

试试这个

 $('select').on('change', function(e){
        console.log( $(this).find('option:selected').attr('data-id') );
    }).change();

OR

或者

$('select').on('change', function(e){
            console.log( $(this).find('option:selected').data('id') );
        }).change();