【问题标题】:jQuery : multi lines operations on an html tablejQuery:对 html 表进行多行操作
【发布时间】:2014-05-17 08:58:36
【问题描述】:

我有一个这样的 html 表格:

time | time_diff
12:01| 
12:21|
12:31|

我如何使用 Javascript(有或没有 jQuery)计算 time_diff,所以我的表格看起来像:

time | time_diff
12:01| 20
12:21| 10
12:31| 

我基本上想知道如何在 html 表格上实现多行操作?

【问题讨论】:

  • 到目前为止你做了什么?
  • 您是从数据库中提取数据吗?如果是这样,您可以在 sql 语句中执行此操作。
  • nop 我无法编辑 sql 查询。我正在编写客户端脚本。

标签: javascript jquery html-table cell lines


【解决方案1】:

可能是这样的:

$('table tbody tr').each(function () {

    var $row = $(this),
        $nextRow = $row.next();

    if ($nextRow.length) {
        this.cells[1].innerHTML = timeDiff($nextRow.find('td').text(), $row.find('td').text());
    }
});

function timeDiff(t1, t2) {
    t1 = t1.split(':');
    t2 = t2.split(':');
    var diff = (t1[0] * 60 + +t1[1]) - (t2[0] * 60 + +t2[1]),
        hours = Math.floor(diff / 60),
        minutes = (diff - hours * 60) + '';
    return hours + ':' + (minutes.length == 1 ? '0' + minutes : minutes);
}

演示:http://jsfiddle.net/vJNa4/1/

【讨论】:

    【解决方案2】:

    类似这样的...

    function set(i, val) { sets value of seconds column, row i }
    function get(i) {returns time from first column, row i;}
    function diff(time1, time2) { returns difference }
    
    last = '';
    for(i=0,i<rows;i++){
     if(i>0) set(i-1, diff(get(i), last));
     last = get(i);
    }
    

    示例实现:

    function set(i, val) { 
       $('table tr:eq('+(i+1)+' td:eq(2))').text(val); 
    }
    function get(i) { 
      return $('table tr:eq('+(i+1)+' td:eq(1))').text();
    }
    function diff(time1, time2) {
      var s1 = time1.split(':');
      var s2 = time2.split(':');
      return s1[0]*60+s1[1] - (s2[0]*60+s2[1]); 
    }
    

    【讨论】:

      猜你喜欢
      • 2011-01-28
      • 1970-01-01
      • 1970-01-01
      • 2012-07-22
      • 2011-06-04
      • 1970-01-01
      • 1970-01-01
      • 2018-02-01
      • 1970-01-01
      相关资源
      最近更新 更多