2016-05-14 92 views
2

所以我有一個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); 
}); 

我做同樣的事情在這之前的數據,價格屬性,並將其返回值的字符串。但它不適用於數據時間屬性。如果有人能夠提供解決方案和解釋,我會非常感謝。

回答

4

你的問題是此行

var currentElement = $('this'); 

this刪除報價與

var currentElement = $(this); 
+0

@Codearts是否解決了您的問題? – gurvinder372

+0

是的。我有正確的數據價格,但沒有注意到我用第二個數據屬性寫了引號。 – Codearts

+0

@Codearts很高興爲你效勞。樂於幫助! – gurvinder372

0

使用$(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