以下代码返回'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>
Run Code Online (Sandbox Code Playgroud)
Jor*_*own 581
您需要找到所选的选项:
$(this).find(':selected').data('id')
Run Code Online (Sandbox Code Playgroud)
要么
$(this).find(':selected').attr('data-id')
Run Code Online (Sandbox Code Playgroud)
虽然第一种方法是首选.
Ric*_*lly 35
请尝试以下方法:
$('select').change(function(){
alert($(this).children('option:selected').data('id'));
});
Run Code Online (Sandbox Code Playgroud)
您的更改订阅者订阅了select的change事件,因此该this参数是select元素.您需要找到所选子项以获取数据ID.
JJa*_*aun 15
也许是更优雅的方式
$('option:selected', this).data('id')
Run Code Online (Sandbox Code Playgroud)
小智 7
document.querySelector('select').onchange = function(){
alert(this.selectedOptions[0].getAttribute('data-attr'));
};
Run Code Online (Sandbox Code Playgroud)
这对我有用
<select class="form-control" id="foo">
<option value="first" data-id="1">first</option>
<option value="second" data-id="2">second</option>
</select>
Run Code Online (Sandbox Code Playgroud)
和脚本
$('#foo').on("change",function(){
var dataid = $("#foo option:selected").attr('data-id');
alert(dataid)
});
Run Code Online (Sandbox Code Playgroud)
您可以将context语法与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'));
});Run Code Online (Sandbox Code Playgroud)
<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>Run Code Online (Sandbox Code Playgroud)
作为微优化的问题,您可能会选择find(). 如果您更像是一个代码高尔夫球手,那么上下文语法会更简短。基本上归结为编码风格。
这里有一个相关的性能比较。
香草Javascript:
this.querySelector(':checked').getAttribute('data-id')
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
256921 次 |
| 最近记录: |