html表行中的值的总和

时间:2016-04-15 08:43:06

标签: javascript jquery

我有这个HTML表格

enter image description here

现在我想显示最后一列的小时数。

我试过这样,它不适合我。

HTML

<table class='Table'>
    <tr><td><span class='hours'>8:16</span></td><td><span class='hours'>8:27</span></td><td><span class='hours'>7:30</span></td><td>Print Sum of duration of this Row</td></tr>
    <tr><td><span class='hours'>6:53</span></td><td><span class='hours'>8:02</span></td><td><span class='hours'>8:17</span></td><td>Print Sum of duration of this Row</td></tr>
    <tr><td><span class='hours'>8:09</span></td><td><span class='hours'>8:28</span></td><td><span class='hours'>8:42</span></td><td>Print Sum of duration of this Row</td></tr>
</table>

Jquery的

$(".Table tr td .hours").each(function(){
    vals1=$(this).html()
    console.log(vals1)
    $(this).parent().parent().parent().find("td:last").html(vals1)
})

从上面的代码我无法确定行尾(TR)。 如果有任何建议可以找到持续时间的总和,将会有所帮助。

1 个答案:

答案 0 :(得分:1)

您可以遍历每个tr并查找字段的总和,如

$(".Table tr:has(.hours)").each(function() {
  var sum = 0;
  $(this).find('td .hours').each(function() {
    var parts = $(this).text().split(':')
    sum += (parts[0] * 60 || 0) + (+parts[1] || 0);
  });
  var mins = Math.floor(sum / 60);
  var sec = sum % 60;
  $(this).find("td:last").html(mins + ':' + ('0' + sec).slice(-2))
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class='Table'>
  <tr>
    <td><span class='hours'>8:16</span>
    </td>
    <td><span class='hours'>8:27</span>
    </td>
    <td><span class='hours'>7:30</span>
    </td>
    <td>Print Sum of duration of this Row</td>
  </tr>
  <tr>
    <td><span class='hours'>6:53</span>
    </td>
    <td><span class='hours'>8:02</span>
    </td>
    <td><span class='hours'>8:17</span>
    </td>
    <td>Print Sum of duration of this Row</td>
  </tr>
  <tr>
    <td><span class='hours'>8:09</span>
    </td>
    <td><span class='hours'>8:28</span>
    </td>
    <td><span class='hours'>8:42</span>
    </td>
    <td>Print Sum of duration of this Row</td>
  </tr>
</table>