繁体   English   中英

如何对 JavaScript 中具有相同类名的表中的所有列求和?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM