表格中的总差异Jquery动态地

时间:2016-01-07 01:29:27

标签: jquery

我将如何在Jquery中执行此操作。我想动态输出每个表行的总差异。谢谢

<table>
   <tr>
      <td><input value = "5"/></td>
      <td><input value = "3"/></td>          
      <td class="total_diff">2</td>
   </tr>
   <tr>
      <td><input value = "10"/></td>
      <td><input value = "3"/></td>
      <td class="total_diff">7</td>
   </tr>
   <tr>
      <td><input value = "16"/></td>
      <td><input value = "4"/></td>
      <td class="total_diff">12</td>
   </tr>
</table>

1 个答案:

答案 0 :(得分:1)

使用.each() method迭代tr元素,根据input元素索引(使用:eq() selector)获取td元素的值,减去值并添加文本。

&#13;
&#13;
$('table tr').each(function() {
  var firstValue = parseInt($(this).find('td:eq(0) input').val(), 10),
      secondValue = parseInt($(this).find('td:eq(1) input').val(), 10);
      
  $(this).find('.total_diff').text(firstValue - secondValue);
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
   <tr>
      <td><input value="5"/></td>
      <td><input value="3"/></td>          
      <td class="total_diff"></td>
   </tr>
   <tr>
      <td><input value="10"/></td>
      <td><input value="3"/></td>
      <td class="total_diff"></td>
   </tr>
   <tr>
      <td><input value="16"/></td>
      <td><input value="4"/></td>
      <td class="total_diff"></td>
   </tr>
</table>
&#13;
&#13;
&#13;