选择更改时,获取数据属性值


273

以下代码返回“未定义” ...

$('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).find(':selected')或$(this).children('option:selected')更好吗?
userBG 2011年

Answers:


640

您需要找到选定的选项:

$(this).find(':selected').data('id')

要么

$(this).find(':selected').attr('data-id')

尽管首选第一种方法。


我在我的初始帖子中错误地使用了attr(),我的意思是data(),但它为我返回了“未定义”。
userBG 2011年

6
我刚刚遇到了这个问题,我想知道第一种方法是由于性能原因还是其他原因而被首选?@JordanBrown
Clarkey

1
@Clarkey我的猜测是data()比attr()更快,因为attr()必须做额外的工作才能确定它是什么类型的属性。只是一个猜想。
dev_willis

37

尝试以下方法:

$('select').change(function(){
  alert($(this).children('option:selected').data('id'));
});

您的变更订阅者订阅了select的change事件,因此this参数是select元素。您需要找到所选的子项以获取数据ID。


截至2016年,这种情况甚至find()children()我们只有2棵树深的情况还要快得多
。– Hafenkranich

9
document.querySelector('select').onchange = function(){   
   alert(this.selectedOptions[0].getAttribute('data-attr')); 
};

请始终努力在StackOverflow上为您发布的代码块提供解释和/或参考(即使解决方案很简单/“不言自明”),因为并非所有人都熟悉给定语言的语法/行为/性能。
mickmackusa

7

香草Javascript:

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

请始终努力在StackOverflow上为您发布的代码块提供解释和/或参考(即使解决方案很简单/“不言自明”),因为并非所有人都熟悉给定语言的语法/行为/性能。
mickmackusa

5

您可以将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'));
});
<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()。如果您更喜欢编码高尔夫球手,则上下文语法会更简短。基本上可以归结为编码风格。

这是一个相关的性能比较


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

1
请始终努力在StackOverflow上为您发布的代码块提供解释和/或参考(即使解决方案很简单/“不言自明”),因为并非所有人都熟悉给定语言的语法/行为/性能。
mickmackusa

OP id在select元素上没有属性(并且由于的效用而不需要属性this)。
mickmackusa

1

这对我有用

<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)
});

1
请始终努力在StackOverflow上为您发布的代码块提供解释和/或参考(即使解决方案很简单/“不言自明”),因为并非所有人都熟悉给定语言的语法/行为/性能。
mickmackusa
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.