下面的代码返回'undefined'…

$('select').change(function(){
    alert($(this).data('id'));
});

<select>
    <option data-id="1">one</option>
    <option data-id="2">two</option>
    <option data-id="3">three</option>
</select>

当前回答

$('#foo option:selected').data('id');

其他回答

您可以使用this或$(this)上下文语法。这与find()的效果相同。

$('select').change(function() { console.log('Clicked option value => ' + $(this).val()); <!-- undefined console.log('$(this) without explicit :select => ' + $(this).data('id')); --> <!-- error console.log('this without explicit :select => ' + this.data('id')); --> console.log(':select & $(this) => ' + $(':selected', $(this)).data('id')); console.log(':select & this => ' + $(':selected', this).data('id')); console.log('option:select & this => ' + $('option:selected', this).data('id')); console.log('$(this) & find => ' + $(this).find(':selected').data('id')); }); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <select> <option data-id="1">one</option> <option data-id="2">two</option> <option data-id="3">three</option> </select>

在微优化方面,您可以选择find()。如果您是一个代码爱好者,那么上下文语法就会更简单。这基本上归结于编码风格。

这里有一个相关的性能比较。

香草Javascript:

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

这对我很有用

<select class="form-control" id="foo">
    <option value="first" data-id="1">first</option>
    <option value="second" data-id="2">second</option>
</select>

还有剧本

$('#foo').on("change",function(){
    var dataid = $("#foo option:selected").attr('data-id');
    alert(dataid)
});

通过使用这个,您可以获得文本,值和数据属性。

<select name="your_name" id="your_id" onchange="getSelectedDataAttribute(this)">
    <option value="1" data-id="123">One</option>
    <option value="2" data-id="234">Two</option>
</select>

function getSelectedDataAttribute(event) {
    var selected_text = event.options[event.selectedIndex].innerHTML;
    var selected_value = event.value;
    var data-id = event.options[event.selectedIndex].dataset.id);    
}
 alert($(this).first().data('id'));