简体   繁体   English

JavaScript-获取数据属性值返回未定义

[英]JavaScript - Getting value of data attribute returns undefined

So I have a data-time attribute that holds an integer value fetched from my database. 因此,我有一个data-time属性,其中包含一个从数据库中获取的整数值。 I get the value of it but it returns undefined. 我得到它的值,但返回未定义。 I inspected the browser and my data-time attribute stores the value correctly. 我检查了浏览器,并且我的data-time属性正确存储了该值。 It is really strange because I am doing the same thing before that and it doesn't return undefined. 真的很奇怪,因为在此之前我正在做同样的事情,并且它不会返回未定义的内容。 Here is my code: 这是我的代码:

<option data-price="{{ $availableOption->price * $course }}" data-time="{{ $availableOption->delivery_time }}">
...
</option

Script 脚本

$('.config-option option:selected').each(function() {
    var currentElement = $('this');
    var optionDeliveryTimeStr = currentElement.attr('data-time');
    console.log(optionDeliveryTimeStr);
});

I do the exact same thing before that with the data-price attribute and it returns the value as string. 在此之前,我使用data-price属性进行了完全相同的操作,它以字符串形式返回值。 But it doesn't work with the data-time attribute. 但这不适用于data-time属性。 If someone could offer a solution and an explanation I would be very thankful. 如果有人可以提供解决方案和解释,我将非常感谢。

Your problem is this line 你的问题是这条线

 var currentElement = $('this');

remove quotes from this and replace it with 从报价中移除this ,取而代之的是

 var currentElement = $(this);

Use $(currentElement) instead of currentElement: 使用$(currentElement)代替currentElement:

$('.config-option option:selected').each(function() {
    var currentElement = $(this);
    var optionDeliveryTimeStr = $(currentElement).attr('data-time'); // OR $(currentElement).data('time');
    console.log(optionDeliveryTimeStr);
});

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

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