我正在嘗試使用名爲jRating的好插件,當我點擊星星時,它應該會進行某種AJAX調用。它是這樣做的,具有正確的費率值,但data-id
屬性(它將作爲AJAX調用文件中的MySQL查詢的輸入)未定義(NaN)。這是代碼:使用jQuery讀取「data-id」屬性
演示HTML:
<div class="exemple">
<!-- in this exemple, 12 is the average and 1 is the id of the line to update in DB -->
<div class="basic" data-average="12" data-id="1"></div>
</div>
//Line 60:
//idBox = parseInt($(this).attr('data-id')), // old version, idBox=Nan
idBox = parseInt($(this).data("id")); // my version, still idBox=Nan
編輯: 主PHP頁面的頭部jQuery的電話:
<script type="text/javascript">
$(document).ready(function(){
$(".exemple").jRating({
length:10,
decimalLength:0,
onSuccess : function(){
alert('Success : your rate has been saved :)');
},
onError : function(){
alert('Error : please retry');
}
});
});
</script>
我似乎無法弄清楚什麼是錯的。請幫我找到它。 謝謝!
SOLUTION:
作爲@ZachL認可, $(this)
,在jRating.jquery.js指的是div.exemple,而該數據ID是在div.basic。
因此改變$(this).data("id")
到$(this).find('.basic').data("id")
工作。
我想象一下'$(this)'的問題。當你記錄下來時,你會得到什麼? – 2013-04-04 22:28:28
'this'指向'div.basic'或'div.exemple'還是別的? – biziclop 2013-04-04 22:29:13
我同意扎克。 '$(this)'可能不是你認爲它的元素,因爲$(this).data(「id」)'應該工作。 – Steve 2013-04-04 22:29:34