简体   繁体   English

JQuery将特定表行中的所有数据相加

[英]JQuery sum all data in specific table row

I have a table with inputs in each cell, except one (.total) which specifies the total of each table row. 我有一个表在每个单元格中有输入,除了一个(.total),它指定每个表行的总和。 When one of the inputs are changed I would like the sum to change for that row. 当其中一个输入被更改时,我希望该行的总和发生变化。 Below is far as I have been able to get. 以下是我能够得到的。 The HTML: HTML:

<table>
   <tr>
      <td><input value = "100"/></td>
      <td><input value = "100"/></td>
      <td><input value = "100"/></td>
      <td class="total">300</td>
   </tr>
   <tr>
      <td><input value = "200"/></td>
      <td><input value = "200"/></td>
      <td><input value = "200"/></td>
      <td class="total">600</td>
   </tr>
</table>

Now for the jQuery: 现在为jQuery:

    //add keyup handler
    $(document).ready(function(){
        $("input").each(function() {
            $(this).keyup(function(){
                newSum();
            });
        });
    });

    function newSum() {
        var sum = 0;
        var thisRow = $(this).closest('tr');

        //iterate through each input and add to sum
        $(thisRow).("td:not(.total) input:text").each(function() {
                sum += this.value;            
        });

        //change value of total
        $(thisRow).(".total").html(sum);
    }

Any help in finding out what I've done wrong will be greatly appreciated. 任何有助于找出我做错了什么的帮助都将不胜感激。 Thanks! 谢谢!

Your main problem is the use of this in your function. 您的主要问题是在您的函数中使用this If you place the body of that function directly in the keyup handler, it should work. 如果将该函数的主体直接放在keyup处理程序中,它应该可以工作。 But this in the body of a separately declared function will refer, essentially, to the object of which it is a method. 但是this在单独声明的函数的体将指,基本上,向其中它是一个方法的对象。 And that object, in the case above, would be window . 在上面的例子中,该对象将是window

Try this: 尝试这个:

$(document).ready(function(){
    $("input").each(function() {
        var that = this; // fix a reference to the <input> element selected
        $(this).keyup(function(){
            newSum.call(that); // pass in a context for newsum():
                               // call() redefines what "this" means
                               // so newSum() sees 'this' as the <input> element
        });
    });
});

You also have some more superficial errors in newSum() : 你在newSum()也有一些更肤浅的错误:

function newSum() {
  var sum = 0;
  var thisRow = $(this).closest('tr');

  thisRow.find('td:not(.total) input:text').each( function(){
    sum += parseFloat(this.value); // or parseInt(this.value,10) if appropriate
  });

  thisRow.find('td.total input:text').val(sum); // It is an <input>, right?
}

I can find a couple of problems and improvements 我可以找到一些问题和改进

  1. summing text values will concatenate all the input values, not the numeric values. 求和文本值将连接所有输入值,而不是数值。 You have to cast the text value to a number using eg parseInt or parseFloat . 您必须使用例如parseIntparseFloat将文本值parseInt转换为数字。
  2. $(this).closest('tr') doesn't return a set. $(this).closest('tr')不返回一组。 You can change this to $(event.target).closest('tr') if you pass the event object from the event handler. 如果从事件处理程序传递事件对象,则可以将其更改为$(event.target).closest('tr') The reason for this is that this is evaluated in the default context not in the context of the event. 原因是this是在默认上下文中而不是在事件的上下文中进行评估。
  3. You should probably use the onchange event instead of onkeyup event: There is no need to update the sum with incomplete information. 您应该使用onchange事件而不是onkeyup事件:不需要使用不完整的信息更新总和。
  4. You can bind the event using $(selector).keyup(function() {}) , you don't need to use the .each function. 您可以使用$(selector).keyup(function() {})绑定事件,您不需要使用.each函数。
  5. JSLint will warn you if you use a function before defining it. 如果在定义函数之前使用函数,JSLint将发出警告。
  6. td:not(.total) input:text is a bit specific in the current context - it can be simplified. td:not(.total) input:text在当前上下文中有点特定 - 它可以简化。

Solution with some modifications 解决方案有一些修改

function newSum(event) {
    var sum = 0;
    var thisRow = $(event.target).closest('tr');
    thisRow.find("td input").each(function() {
        sum += parseInt(this.value);
    });


    thisRow.find(".total").html(sum);
}

$("input").change(function(event) {
    newSum(event);
});

The composition might be better if the newSum-function didn't have to know about the context as much eg 如果newSum函数不必了解上下文,那么组合可能会更好

function sumInputsIn(inputs) {
    var sum = 0;
    inputs.each(function() {
        sum += parseInt(this.value, 10);
    });
    return sum;
}

$("input").change(function(event) {
    var row = $(event.target).closest('tr');
    row.find('.total').html(sumInputsIn(row.find('td input')));
});

There are a few things wrong that the below should resolve. 以下问题应该解决一些问题。

  1. newSum is called with the wrong context (the default window context, not the context of the DOM object) 使用错误的上下文调用newSum(默认窗口上下文,而不是DOM对象的上下文)
  2. an invalid selector is used to find the input fields 无效的选择器用于查找输入字段
  3. the values you're summing will be treated as text unless you use parseInt 除非您使用parseInt,否则您要求的值将被视为文本

Code: 码:

//add keyup handler
$(document).ready(function(){
    $("input").each(function() {
        $(this).keyup(function(){
            newSum.call(this);
        });
    });
});

function newSum() {
    var sum = 0;
    var thisRow = $(this).closest('tr');
    //iterate through each input and add to sum
    $(thisRow).find("td:not(.total) input").each(function() {
            sum += parseInt(this.value);    
    });

    //change value of total
    $(thisRow).find(".total").html(sum);
}
$(document).ready(function(){  
    $("input").keyup(function(){
        var suma = 0; 
        $(this).parents("tr").children("td").children().each(function(){
            suma+= parseInt($(this).val());
        });
        $(this).parent().parent().children(":last").text(suma);
    });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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