下面的代码返回'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>
下面的代码返回'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>
当前回答
也许是一种更优雅的方式
$('option:selected', this).data('id')
其他回答
$('#foo option:selected').data('id');
通过使用这个,您可以获得文本,值和数据属性。
<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'));
您可以使用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()。如果您是一个代码爱好者,那么上下文语法就会更简单。这基本上归结于编码风格。
这里有一个相关的性能比较。
也许是一种更优雅的方式
$('option:selected', this).data('id')