将开始和结束时间分配给表格单元格并检查当前时间

时间:2015-03-26 10:25:21

标签: javascript jquery html

我有一个HTML表格,其中包含某些事件的开始和结束时间。有没有办法为每个表格单元分配开始和结束时间,然后检查当前时间是否在每个单元格中的时间之后?

<table class="ui celled  blue table">

  <thead>
    <tr>
      <th>Monday</th>
      <th>Tuesday</th>
      <th>Wednesday</th>
      <th>Thursday</th>
      <th>Friday</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td class="clickable">08:30 - 09:30 Meeting</td>
    </tr>
    <tr>
      <td class="clickable">08:30 - 09:30 Meeting</td>

    </tr>
    <tr>
      <td class="clickable">08:30 - 09:30 Meeting</td>

    </tr>

    <tr>
      <td class="clickable">08:30 - 09:30 Meeting</td>
    </tr>

    <tr>
      <td class="clickable">08:30 - 09:30 Meeting</td>
    </tr>

    <tr>
      <td class="clickable">08:30 - 09:30 Meeting</td>
    </tr>

    <tr>
     <td class="clickable">08:30 - 09:30 Meeting</td>
    </tr>
  </tbody>

</table>

1 个答案:

答案 0 :(得分:0)

发布你的代码,让我更多地了解你想要做什么...但是这样的东西会起作用(使用jQuery),如果你需要原始的JavaScript回发,我会转换它。

var now = new Date();
$('table#tableid td').each(function()
{
  var td = $(this);

  // get cell text or assign start and end date to the cell
  // like this to add it as an attribute
  // td.attr('data-start-date', new Date());

  // to get an attribute you can use
  // var start = td.attr('data-start-date'); 
  // where there is an attribute data-start-date on the td element

  var date = new Date(td.text()); // you may need to consider date format string of the cell text
  if(date > now)
  {
    console.log(date + ' is after now.');
    // you could also color the cell if you needed like
    td.addClass('green'); // then create a css class for .green { background: green; }
  }
});

此处的JavaScript日期对象文档https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date

解析您的手机信息的示例

A 'simple' JSBin example假设单元格文本中有24小时的时间。更改一些单元格值,您将看到绿色。此外,没有关于日期的验证 - 例如,开始是在结束之后。

注意我的建议(在注释中,关于属性)因为字符串解析很讨厌,如果可以避免它应该是。

日期操作有用(易于使用)的库是moment.js

$(function()
{
  var now = new Date(); 

  var getTimeFromString = function(timeStr)
  {
    var split = timeStr.split(':');
    return { 
      hour: split[0], 
      minute: split[1] 
    };
  };

  var getTimeFromCellText = function(text)
  {    
    var split = text.split(' ');    
    var time = 
    {
      start: getTimeFromString(split[0]),
      end: getTimeFromString(split[2])
    };

    return time;
  };

  $('table.celled td').each( 
    function() 
    {
      var td = $(this);
      var time = getTimeFromCellText(td.text()); 

      var start = new Date(now);
      start.setHours(time.start.hour);
      start.setMinutes(time.start.minute);

      var end = new Date(now);
      end.setHours(time.end.hour);
      end.setMinutes(time.end.minute);

      if(now > start && now < end)
      {
        td.addClass('green');   
      }
    });
});