![](/img/trans.png)
[英]How can I select the all classes in javaScript with same classname?
[英]How do I sum all columns in a table with the same classname in JavaScript?
我試圖在表格中總結價格, <td>
中的所有價格都具有相同的 class 名稱,我想通過單擊按鈕來總結它們。 我最終也想將數量計算到總數中。 這是我到目前為止所擁有的:
function sumAmounts() { var sum = 0; var listPriceTotal = $('.txtListPrice').each(function() { sum += parseFloat($(this).html); // Or this.innerHTML, this.innerText }); document.getElementById("txtTotal").value = listPriceTotal; } document.getElementById("addTotals").addEventListener("click", () => { sumAmounts(); });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <table id="table"> <tr> <th><label>SKU</label></th> <th><label>Retail Price</label></th> <th><label>List Price</label></th> <th><label>Product Name</label></th> <th><label>Quantity</label></th> </tr> <tr> <td class="txtSKU">1234</td> <td class="txtRetailPrice">12.50</td> <td class="txtListPrice">11.75</td> <td class="txtProductName">product 1</td> <td class="txtQuantity"><input type="text"> </td> </tr> <tr> <td class="txtSKU">12222</td> <td class="txtRetailPrice">14.50</td> <td class="txtListPrice">9.75</td> <td class="txtProductName">product 2</td> <td class="txtQuantity"><input type="text"> </td> </tr> <tfoot> <th><label id="lblTotal">Total:</label><input type="text" name="txtTotal" id="txtTotal"> <input type="button" value="Add" id="addTotals"> </th> </tfoot> </table>
您的代碼中有兩個問題。 首先,您嘗試將 jQuery object 設置為input
的值,這就是您在字段中看到[Object object]
的原因。 您需要將值設置為sum
。
第二個問題是您提供html
方法參考parseFloat()
,而不是實際的html()
值。 解決了這兩個問題后,代碼可以工作:
function sumAmounts() { var sum = 0; $('.txtListPrice').each(function() { sum += parseFloat($(this).html()); }); document.getElementById("txtTotal").value = sum; } document.getElementById("addTotals").addEventListener("click", () => { sumAmounts(); });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <table id="table"> <tr> <th><label>SKU</label></th> <th><label>Retail Price</label></th> <th><label>List Price</label></th> <th><label>Product Name</label></th> <th><label>Quantity</label></th> </tr> <tr> <td class="txtSKU">1234</td> <td class="txtRetailPrice">12.50</td> <td class="txtListPrice">11.75</td> <td class="txtProductName">product 1</td> <td class="txtQuantity"><input type="text"> </td> </tr> <tr> <td class="txtSKU">12222</td> <td class="txtRetailPrice">14.50</td> <td class="txtListPrice">9.75</td> <td class="txtProductName">product 2</td> <td class="txtQuantity"><input type="text"> </td> </tr> <tfoot> <th> <label id="lblTotal">Total:</label> <input type="text" name="txtTotal" id="txtTotal"> <input type="button" value="Add" id="addTotals"> </th> </tfoot> </table>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.