下面的代码返回'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>
发布于 2011-12-02 01:32:17
您需要找到所选的选项:
$(this).find(':selected').data('id')
或
$(this).find(':selected').attr('data-id')
虽然第一种方法是首选的。
发布于 2011-12-02 01:35:14
尝试以下操作:
$('select').change(function(){
alert($(this).children('option:selected').data('id'));
});
change订阅服务器订阅select的更改事件,因此this
参数是select元素。您需要找到要从中获取data-id的所选子对象。
发布于 2017-01-30 23:17:44
document.querySelector('select').onchange = function(){
alert(this.selectedOptions[0].getAttribute('data-attr'));
};
https://stackoverflow.com/questions/8345666
复制相似问题