简体   繁体   English

jQuery从选择器获取实际的数据ID

[英]jQuery get actual data-id from selector

I have a selector on webpage with data-id and value 我在网页上有一个带有数据ID和值的选择器

HTML 的HTML

    <select id="s1">
        <option data-id="01">aaaa1</option>
        <option data-id="23">bbb1</option>
        <option data-id="451">ccc1</option>
        <option data-id="56">ddd1</option>

    </select>

<p></p>

JAVASCRIPT JAVASCRIPT

$('#s1').change(function() { 
       var val = $(this).val();   
       var val_id =$(this).find('option').data('id');
       $("p").html("value = " + val + "<br>" +"value-data-id = "+  val_id);
});

I wanna have actual value from selected selector and his data-id. 我想从选定的选择器及其数据ID中获取实际值。 I do not understand why I have data-id from only first option. 我不明白为什么我只有第一个选项具有data-id。 This is my code http://jsfiddle.net/s55rR/ Please help me to find a bug. 这是我的代码http://jsfiddle.net/s55rR/请帮助我查找错误。

您可以执行$(this).find('option:selected').data('id')

You've selected multiple elements ( $(this).find('option') ) but .data() only returns the value from the first element if called on a jQuery with length >1: 您已经选择了多个元素$(this).find('option') ),但是.data()仅在长度大于1的jQuery上调用时才返回第一个元素的值:

Description: Return the value at the named data store for the first element in the jQuery collection, as set by data(name, value) or by an HTML5 data-* attribute. 说明: 返回在命名数据存储中jQuery集合中第一个元素的值,该值由data(name, value)或HTML5 data-*属性设置。

If you only want the data-id value from the user-selected <option> , then you need to select only that element. 如果只需要用户选择的<option>data-id值,则只需选择该元素。

Because you selecting all options, and jQuery returning .data('id') of first one 因为选择所有选项,并且jQuery返回第一个选项的.data('id')

var val_id =$(this).find('option:selected').data('id');

fiddle 小提琴

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM