使用jQuery自动更新类似Excel的表格单元格

使用jQuery自动更新类似Excel的表格单元格,jquery,excel,auto-update,cells,Jquery,Excel,Auto Update,Cells,我有一个HTML表结构,它看起来大致如下: PRICE QUANTITY TOTAL [5____] [2____] 10 (TOTAL1=PRICE1*QUANTITY1) 价格和数量列中的值是可编辑的。这些是HTML表单字段 “总计”列中的值不可编辑。相反,它们是左侧列的直接函数 该表的HTML表示形式为: <table id="some_id"> <tr> <td><input type="text"

我有一个HTML表结构,它看起来大致如下:

PRICE       QUANTITY    TOTAL
[5____]     [2____]     10 (TOTAL1=PRICE1*QUANTITY1)
价格和数量列中的值是可编辑的。这些是HTML表单字段

“总计”列中的值不可编辑。相反,它们是左侧列的直接函数

该表的HTML表示形式为:

<table id="some_id">
  <tr>
    <td><input type="text" name="price1" value="5" /></td>
    <td><input type="text" name="quantity1" value="2" /></td>
    <td><input type="readonly" name="total1" /></td>
  </tr>
</table>

使用jQuery,我希望使“total1”的值始终反映“price1”乘以“quantity1”的值

问:我知道有很多方法可以实现这一点,但是使用jQuery最干净、最简洁的方法是什么

因为“自动更新/派生字段”应该是一个非常常见的jQuery用例,所以我假设存在一些最佳实践方法来实现这一点。

The()解决了这个确切的问题

下面的代码显示了如何使用jQuery计算来解决此特定情况下的问题:

function recalc() {
  $("[name=total1]").calc(  
    "p * q",
    {   
      q: $("input[name=quantity1]"),
      p: $("input[name=price1]")
    },
    function (s) {
      // set number of decimals of resulting value to zero
      return s.toFixed(0);
    },
    function (t) {
      // this runs after the calculation has been completed
    }
  );
}
$("input[name=price1]").bind("keyup", recalc);
$("input[name=quantity1]").bind("keyup", recalc);
recalc();

这应该可以做到:

$('input[name^="price"], input[name^="quantity"').keyup(function() {
    $rowTds = $(this).closest('tr').children('td'); // get the row tds
    price = $rowTds.eq(0).children('input').val(); // get the price
    quantity = $rowTds.eq(1).children('input').val(); // get the quantity
    $rowTds.eq(2).children('input').val(price * quantity); // store the value in the total field
});
这可能会缩短为2行(在函数内部),但我认为这样可以保持可读性