无法使用jQuery获取数据属性的值

时间:2022-05-14 20:34:17

Here it's my html code

这是我的html代码

<select class="changeOption">
 {% for dBoy in dBoyList %}
    <option value="{{dBoy.id}}" data-locid='{{dboy.location.id}}'
 {% endfor %} 
</select>

When i'm select any option from dropdown list it shows undefine

当我从下拉列表中选择任何选项时,它会显示undefine

JQuery code

JQuery代码

$( ".changeOption" ).change(function() {
    var locId = $(this).data("locid")
    alert("id:  "+locId);
});

1 个解决方案

#1


4  

this refers to context of select element. you need to find selected option in it and then get the attribute:

这指的是select元素的上下文。您需要在其中找到所选的选项,然后获取属性:

$(".changeOption").change(function() {
  var locId = $(this).find(':selected').data("locid")
  alert("id:  "+locId);
});

#1


4  

this refers to context of select element. you need to find selected option in it and then get the attribute:

这指的是select元素的上下文。您需要在其中找到所选的选项,然后获取属性:

$(".changeOption").change(function() {
  var locId = $(this).find(':selected').data("locid")
  alert("id:  "+locId);
});