JavaScript - 获取数据属性值返回undefined

问题描述:

所以我有一个data-time属性,它保存从我的数据库中提取的整数值。我得到它的价值,但它返回undefined。我检查了浏览器,我的data-time属性正确存储了这个值。 这真的很奇怪,因为我在此之前做了同样的事情,它不会返回undefined。这里是我的代码:JavaScript - 获取数据属性值返回undefined

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

脚本

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

我做同样的事情在这之前的数据,价格属性,并将其返回值的字符串。但它不适用于数据时间属性。如果有人能够提供解决方案和解释,我会非常感谢。

你的问题是此行

var currentElement = $('this'); 

this删除报价与

var currentElement = $(this); 
+0

@Codearts是否解决了您的问题? – gurvinder372

+0

是的。我有正确的数据价格,但没有注意到我用第二个数据属性写了引号。 – Codearts

+0

@Codearts很高兴为你效劳。乐于帮助! – gurvinder372

使用$(currentElement),而不是currentElement:

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

'$取代它(currentElement ).attr('data-time');'=='$($(this))。attr('data-time');'? – guradio