gpt-4.1-mini-2025-04-14· OpenAI WildChat-4.8M (AI2)
我的網站有以下編碼: <div id="cart-container" class="col-xl-9 col-lg-8"> <?php foreach($finalData…
- User
我的網站有以下編碼:
</div> </div> <div class="item-total-price"><span class="product-line-price text-lg h6 mb-0 fw-semibold" data-value="<?=$row['total']?>"><?= $row['total'] ?></span></div> </div> </div> </div> <?php } ?> </div> </div> <?php } ?> </div>我想用Javascript / Jquery的方式,得出所有store-group中的所有item-total-price中的product-line-price的總和
- Assistant
你可以使用 jQuery 來遍歷每個
.store-group,並對該區塊中所有.product-line-price的值進行加總。以下範例示範如何取得每個 store-group 中的總和,並且在控制台列出結果:$('#cart-container .store-group').each(function() { var storeName = $(this).data('store'); var totalSum = 0; $(this).find('.product-line-price').each(function() { // 取得 data-value 屬性 (數字格式) var val = parseFloat($(this).data('value')) || 0; totalSum += val; }); console.log('Store: ' + storeName + ' 總和為: ' + totalSum); });
如果你想要把每個總和顯示在對應的
.store-group中,可以加個元素顯示或更新內容。例如在每個.store-group的底部加入一個顯示總價的區塊:<div class="store-total"></div>然後用 jQuery 更新內容:
$('#cart-container .store-group').each(function() { var totalSum = 0; $(this).find('.product-line-price').each(function() { var val = parseFloat($(this).data('value')) || 0; totalSum += val; }); // 顯示總和 $(this).find('.store-total').text('小計: ' + totalSum.toFixed(2)); });
注意:
data-value目前你的 HTML 中存的是<?= $row['total'] ?>,請確認數值型態正確 (無空白、非字串等)- 若需四捨五入或格式化金額,可用
toFixed(2)或其他方法 - 如果使用純 JavaScript,也可以類似寫法,使用
document.querySelectorAll等方法遍歷
需要我幫你寫完整加入頁面顯示的範例可以告訴我!
- User
我想計算所有Store的總和
- Assistant
如果你想計算所有 store-group 裡面所有 product-line-price 的總和,即整個購物車的總價,你可以用 jQuery 這樣寫:
var grandTotal = 0; $('#cart-container .product-line-price').each(function() { var val = parseFloat($(this).data('value')) || 0; grandTotal += val; }); console.log('所有 Store 的總和為: ' + grandTotal.toFixed(2));說明:
- 選取所有
.product-line-price元素 - 讀取它們的
data-value屬性,轉為數字並累加 - 以
toFixed(2)格式化為兩位小數
你也可以把結果顯示在頁面上,例如放到某個 id 為
grand-total的元素:<div id="grand-total"></div>$('#grand-total').text('購物車總金額:' + grandTotal.toFixed(2));需要範例範本整合,或純 JavaScript 版也可以告訴我!
- 選取所有