下面的代码返回'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>
当前回答
您可以使用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()。如果您是一个代码爱好者,那么上下文语法就会更简单。这基本上归结于编码风格。
这里有一个相关的性能比较。
其他回答
document.querySelector('select').onchange = function(){
alert(this.selectedOptions[0].getAttribute('data-attr'));
};
香草Javascript:
this.querySelector(':checked').getAttribute('data-id')
试试下面的方法:
$('select').change(function(){
alert($(this).children('option:selected').data('id'));
});
您的更改订阅者订阅了选择的更改事件,因此this参数是选择元素。您需要找到要从中获取数据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);
}
也许是一种更优雅的方式
$('option:selected', this).data('id')