[英]Get total of all data attribute values
我正在頁面中動態加載一些內容,並希望獲得所有數據屬性的總計。
首先,將元素克隆並附加
$('.chip').on('click', function () {
$(this).clone().appendTo('.chipPlacement');
});
然后我寫了一個應該得到總數的函數
function chipsBet() {
var redchip = $('.chipPlacement .chipValue.r').data() || 0;
var bluechip = $('.chipPlacement .chipValue.b').data() || 0;
var orangechip = $('.chipPlacement .chipValue.o').data() || 0;
var total = redchip.chipValue + bluechip.chipValue + orangechip.chipValue;
return total;
}
在添加元素之前,HTML看起來像
<div class="chipPlacement"></div>
並且一旦附加了HTML結構,
<div class="chipPlacement">
<div class="chip red">
<div class="chipValue r" data-chip-value="1">1</div>
</div>
</div>
我需要偵聽DOM結構的更改,然后啟動chipsBet()
函數,但是我不確定如何chipsBet()
起作用。 我不能使用.on('change')
因為它僅適用於input
, textarea
和select
。
我曾嘗試在.chip.on('click')
觸發chipsBet
函數,但返回NaN
。
如何獲取DOM中新元素的data-attribute-values
?
如果您沒有藍籌碼或橙籌碼,則實際上是在嘗試.chipValue
undefined
0
中獲取.chipValue
,並將其添加到另一個數字中得到NaN
。
您可以像這樣簡單地遍歷放置元素中的所有.chipValue
元素:
function chipsBet()
{
var total = 0;
$('.chipPlacement .chipValue').each(function() {
total += $(this).data('chipValue');
});
return total;
}
沒關系,您更改了最初的問題..繼續。
<div class='chipPlacement'>
<div class='chip red'>
<div class='chipValue' data-chip-value='1'></div>
</div>
</div>
然后,要讀取數據屬性,您可以執行以下操作。
$('.chip').on('click', function () {
$(this).clone().appendTo('.chipPlacement');
chipsBet();
});
function chipsBet() {
var redchipVal = parseInt($('.chipValue .r').data('chip-value')) || 0;
var bluechipVal = parseInt($('.chipValue .b').data('chip-value')) || 0;
var orangechipVal = parseInt($('.chipValue .o').data('chip-value')) || 0;
var total = redchipVal + bluechipVal + orangechipVal;
return total;
}
我想你想要像波紋管這樣的東西。 每當div .chipPlacement
任何更改時,它將調用該函數。
$('.chipPlacement').bind("DOMSubtreeModified",function(){
console.log('Div modified');
});
你可以說你的問題
$('.chipPlacement').bind("DOMSubtreeModified",function(){
chipsBet();
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.