jquery计算表中行的值

时间:2014-05-02 13:46:10

标签: jquery

这是我在jsfiddle上的代码

Visit

 $(document).ready(function(){

 //iterate through each textboxes and add keyup
 //handler to trigger sum event
 $("#targetPrice1").each(function() {

        $(this).keyup(function(){
            calculateSum();
        });
    });

});

function calculateSum() {

    var sum = 0;

    //iterate through each textboxes and add the values
    $("#targetPrice1").each(function() {
    var targetprice = $("#targetPrice1").val();
    var share = $("#share1").text();
    var cb = $("cb1").text();
        //add only if the value is number
        if(!isNaN(targetprice) && targetprice.length!=0) {
            sum = parseFloat(targetprice) * share - cb;

        }

    });
    //.toFixed() method will roundoff the final sum to 2 decimal places
    $("#rowSum1").html(sum.toFixed(2));
}

我要做的是根据每行的值进行计算。 (就像第1行的工作方式一样)

但我想迭代每一行。 (行中的类名简单地递增。比如share1 - > share2从row1到row2)

我如何编码以使其有效?

2 个答案:

答案 0 :(得分:0)

这是怎么做的。我已经评论过了,你可以理解:)

http://jsfiddle.net/jabark/C4Pn8/3/

$(".targetPrice").each(function () { // Loop through all items will class of targetPrice
   $(this).keyup(function () {
      calculateSum($(this)); // Send the input through to the function
   });
});

答案 1 :(得分:0)

你不必做任何复杂的循环,只需这样做 -

$(document).ready(function () {
    $('.targetPrice').keyup(function() {
        var sum = 0;
        var targetPrice = $(this).val();
        var share = parseInt( $(this).closest('tr').find('.share').text() );
        var cb = parseInt( $(this).closest('tr').find('.cb').text() );
        if (!isNaN(targetPrice) && targetPrice.length != 0) {
          sum = parseFloat(targetPrice) * share - cb;
        }
        $(this).closest('tr').find(".rowSum").html(sum.toFixed(2));
    });
});

http://jsfiddle.net/C4Pn8/4/

请注意,我为每个行的单元格分配了相同的类,这样您就不必担心id了 - 所以你需要修改标记才能这样做。