javascript - JQuery 求和特定表行中的所有数据

标签 javascript jquery

我有一个表格,每个单元格都有输入,除了一个 (.total) 指定每个表格行的总数。当其中一个输入发生变化时,我希望该行的总和发生变化。以下是我所能得到的。 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>

现在是 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);
    }

任何帮助找出我做错了什么的人都将不胜感激。谢谢!

最佳答案

您的主要问题是在函数中使用了 this。如果将该函数的主体直接放在 keyup 处理程序中,它应该可以工作。但是,在单独声明的函数体中的 this 本质上将引用它是其方法的对象。在上面的例子中,该对象将是 window

试试这个:

$(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
        });
    });
});

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?
}

关于javascript - JQuery 求和特定表行中的所有数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5215185/

相关文章:

javascript - 在javascript中接受端口的文本框验证

javascript - 无法在导航点击事件上编辑 div

javascript - react : Am I using conditional rendering wrongly as it seems to not evaluate as expected?

javascript - 使用js或jquery替换w3-include-html attr

jquery - 在 jQuery 中,为什么以编程方式触发复选框上的 'click()' 不会立即检查它?

javascript - 如何单击动态创建的链接,然后从该链接创建新的动态页面?

javascript - 用户登录时在顶部显示用户名

javascript - 为什么我的 <a> 的名称没有随着 for 循环而改变?

jquery - 从顶部删除标题

javascript - 如何在angular js中将给定值附加到数组中