我有一些表格,我需要计算列值。在我的场景中,我需要计算总项目价格99 + 55 = 154到Sub Total Row。在这里,我的小计计算不起作用。



我的代码(表创建的一部分)

  $option.each(function () {
            if ($(this).prop('selected')) {
                var txtId = 'txtQty' + i;
                var lblId = 'lblQty' + i;
                var row = $('<tr><td>' + $(this).text() + '</td><td>' + $(this).attr('RetailPrice') + '</td><td>' + $(this).attr('WholesalePrice') + '</td><td>' + '<input type="text" id="' + txtId + '">' + '</td><td> <button type="button" class="btn btn-warning btn-xs btncalc">Calculate</button></td><td class="tot"><label for="tempprice" id="' + lblId + '"></label></td><td><img id="imgdel" src="../../Images/delete.png" alt="" onclick="deleteclick(this)" title="Delete" /></td></tr>');

                table.append(row);
                i++;
            }

        });
 var row2 = $('<tr><td>' + "SubTotal" + '</td><td></td><td></td><td></td><td></td></tr>');
        table.append(row2);
        $('#product-load-tbl').append(table);
    });


计算部分

    $('.btncalc').live('click', function () {
            debugger;
            var row = $(this).parents("tr:first");
            var rowval = $(row).find("td:eq(1)").html();
            var inpval = $(row).find("td:eq(3) input").val();

            if (inpval != null || inpval != 0) {
                var result = (rowval * inpval);
            }
            else {
                var result = 0;
            }
            $(row).find("td:eq(5)").html(result);

            var lstrow = $(this).parents("tr:last"); // this sub total calculation not working
            $.each($('.tot'), function (element) {

                $(lastrow).find("td:eq(5)").html(element);

            });




        })

最佳答案

您可以更改此:

$.each($('.tot'), function (element) {
   $(lastrow).find("td:eq(5)").html(element);
});


对此:

var total = 0; // intialise a var with value 0
$('.tot').each(function (i, element) { // loop the selected item in each row
   total += +$(this).text(); // cast the string to integer and add it to total
});
$(lastrow).find("td:eq(5)").text(total); // then at last place the total




Short demo



并简短说明:

现在已从最新的jQuery版本中删除了.live(),因此,如果您使用的是version 1.7+,则可以将代码移至.on()方法以委派事件。对于事件委托,语法类似于以下内容:

$(static_parent).on(event, selector, callback);


$(static_parent)是相对dom准备就绪时可用的元素,并且在将任何动态dom元素附加到页面中之前是可用的。

所以在你的情况下:

$('table_ID/Class').on('click', '.btncalc', function(){
    //...all the stuff with .live goes here
});

10-07 19:42
查看更多