我有一个场景,有人可以单击一个按钮并向收据(表格)中添加一个新条目。每次单击该按钮都会添加一个新行,第一列是产品名称,第二列是商品值。所以我想找出项目值单元格的总和。
HTML
<div id="cartSection">
                <table id="tableCart">
                </table>
                <br>
                <div id="summary">
                    <p>Your total is: </p><p id="total123"></p>
                </div>
</div>
JAVASCRIPT
function populateCart(){
    
    var table = document.getElementById("tableCart");
    var subtotal = document.getElementById("subtotalValue");
    var amount = document.getElementById("select3").value;
    var godzilla = "GODZILLA - GODZILLA VS. KONG - 2021 1OZ PURE GOLD COIN ";
    
// Create an empty <tr> element and add it to the 1st position of the table:
    var row = table.insertRow(0);
    row.className = "row1";
// Insert new cells (<td> elements) at the 1st and 2nd position of the "new" <tr> element:
    var cell1 = row.insertCell(0);
    var cell2 = row.insertCell(1);
    cell2.className = "cartItem";
// Add some text to the new cells:
    cell1.innerHTML = amount.toString()+"x "+godzilla;
    cell2.innerHTML = subtotal.innerHTML;
    
    $(document).ready(function(){
        var x, sum;
        var tableCart;
        $(".row1").each(function(){
            tableCart = $(this);
            x = tableCart.closest('.cartItem').val();
            sum += parseInt(x);
            
        });
        $("#total123").html(sum);
      });
}我尝试使用jQuery来计算列的总和,并在计算出总和后,更改显示总和的表格下面的一些文本的innerHTML。我正在尝试将创建的新单元格添加到"cartItem“类中,这样我就可以用jQuery选择它们。文本没有改变,我不知道为什么,所以如果有人可以帮助我,我非常感谢:)
发布于 2021-04-08 03:11:55
您定义的$(document).ready函数仅在文档加载时触发一次。因此,只要加载文档,就会对所有行进行合计,但不是每次添加一行时。您可以将加法运算提取到一个新函数中,然后在单元格中的值发生变化时调用该函数。类似于:
function populateCart(){
  //If neither of these have an actual div in the DOM, they will throw an exception and the rest of the javascript will not process
  var subtotal = document.getElementById("subtotalValue");
  var amount = document.getElementById("select3").value;
  ...
  var cell1 = row.insertCell(0);
  var cell2 = row.insertCell(1);
  cell2.className = "cartItem";
  // Add some text to the new cells:
  cell1.innerHTML = amount.toString()+"x "+godzilla;
  cell2.innerHTML = subtotal.innerHTML;
  sumRows();
}
$(document).ready(function(){
    sumRows();
});
function sumRows() {
    var x, sum;
    var tableCart;
    $(".row1").each(function(){
        tableCart = $(this);
        x = tableCart.closest('tr').find('.cartItem').val();
        sum += parseInt(x);
        
    });
    $("#total123").text(sum);
}实际上,您可能希望侦听添加的新行,然后调用sumRows()函数再次添加总计。或者保留一个运行合计,当添加新行时,只需将该新行的值添加到合计中。
编辑:现在我看到所有的javascript都在一个函数中,我已经更新了代码,以便更好地为您工作。请务必注意,尝试使用$('#total123').text(sum)而不是$("#total123").html(sum);。另外,请注意,您正在尝试获取var amount的.value,其中'select3‘id在DOM中不存在。这将抛出一个错误,并导致javascript无法完成。
https://stackoverflow.com/questions/66992394
复制相似问题