迭代时间的行值并添加

时间:2016-08-12 03:55:34

标签: javascript jquery momentjs

我得到了通过ajax获取数据的动态表,因此它增长和增长,我使用的代码只适用于一行而不是多行,例如http://jsfiddle.net/47uzgx9a/

您可以看到第一行是完美的,但第二行和第三行不是,它输出的时间与第1行和第34行相同; 01:54.397 "我们需要第2行是" 01:54.610 "和第3行是" 01:54.730 "

js code

var sp1 = $('#table tr td:nth-child(2)').text()
var sp2 = $('#table tr td:nth-child(3)').text()
var sp3 = $('#table tr td:nth-child(4)').text()
var1 = moment(sp1, "mm:ss.SSS") + moment(sp2, "mm:ss.SSS") + moment(sp3,"mm:ss.SSS")
$('td:nth-child(5)').html(moment(var1).format("mm:ss.SSS"));

1 个答案:

答案 0 :(得分:2)

您必须遍历每一行并将相应的总数设置为相应的td



$('#table tr').each(function(){
var sp1 = $(this).find('td:nth-child(2)').text()
var sp2 = $(this).find('td:nth-child(3)').text()
var sp3 = $(this).find('td:nth-child(4)').text()
var1 = moment(sp1, "mm:ss.SSS") + moment(sp2, "mm:ss.SSS") + moment(sp3, "mm:ss.SSS")

 $(this).find('td:nth-child(5)').html(moment(var1).format("mm:ss.SSS"));
 });

#table {
	margin: 60px auto;
	font-family: "Lucida Sans Unicode", "Lucida Grande", Sans-Serif;
    font-size: 14px;
    width: 600px;
    table-layout: fixed;
    text-align: left;
    border-collapse: collapse;
}

#table th {
    font-size: 15px;
    font-weight: normal;
    background: #b9c9fe;
    border-top: 4px solid #aabcfe;
    border-bottom: 1px solid #fff;
    color: #039;
    padding: 8px;
}

#table td {
    background: #e8edff;
    border-bottom: 1px solid #fff;
    color: #669;
    border-top: 1px solid transparent;
    padding: 8px;

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.14.1/moment.min.js"></script>

<table id="table">
  <thead>
    <tr>
      <th>Lap</th>
      <th>Split 1</th>
      <th>Split 2</th>
      <th>Split 3</th>
      <th>Total Time</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>1</td>
      <td>0:31.110</td>
      <td>0:50.490</td>
      <td>0:32.797</td>
      <td>(total time)</td>
    </tr>
     <tr>
      <td>2</td>
      <td>0:31.300</td>
      <td>0:50.600</td>
      <td>0:32.710</td>
      <td>(total time)</td>
    </tr>
     <tr>
      <td>3</td>
      <td>0:31.500</td>
      <td>0:50.400</td>
      <td>0:32.830</td>
      <td>(total time)</td>
    </tr>
  </tbody>
</table>
&#13;
&#13;
&#13;