Javascript:根据TD TITLE值更改TD颜色

时间:2016-02-15 06:12:44

标签: javascript css

我需要根据title属性中的时间戳更改表数据颜色。例如,从以下值开始,

  • 如果“部署在”< 1小时TD bg颜色必须为红色,否则
  • 如果“部署在”< 24小时TD bg颜色必须为绿色,否则
  • 如果“已部署”< 1周bd颜色应显示为灰色。那样:
<tr>
  <td title="Deployed on :Wed Mar 25 2015 10:00:00 UTC| check performed on: Wed Feb 14 2015 23:34:00 UTC ">Version 4.0</td>
  <td title="Deployed on :Mon Feb 15 06:05:05 UTC 2016 |check performed on: Mon Feb 15 06:05:05 UTC 2016 ">version 8.3.2</td>
  <td title="None">None</td>
</tr>

如果有任何其他要求,请告诉我。 仅供参考,我正在使用Django&amp; bootstrap css。

非常感谢

编辑:日期格式已修复:“部署日期:星期一2月15日06:05:05 UTC 2016”

2 个答案:

答案 0 :(得分:1)

如果你使用标题,你可以尝试这样的事情:

window.onload = function() {
  var td = document.getElementsByTagName('td');
  for (var i = 0; i < td.length; i++) {
    var title = td[i].getAttribute("title").split("|");
    var titleObj = {}
    title.forEach(function(item) {
      var o = item.split(':');
      var retObj = {};
      if (o.length > 1)
        titleObj[o[0].trim()] = new Date(o[1]);
    });

    if (titleObj["Deployed on"])
      td[i].className = titleObj["Deployed on"].getMonth() < 2 ? "red" : "blue";
  }
}
.red {
  background: red;
  color: white;
}
.blue {
  background: blue;
  color: white;
}
<table>
  <tr>
    <td title="Deployed on :Wed Mar 25 2015 10:00:00 UTC| check performed on: Wed Feb 14 2015 23:34:00 UTC ">Version 4.0</td>
    <td title="Deployed on :Mon Feb 15 06:05:05 UTC 2016 |check performed on: Mon Feb 15 06:05:05 UTC 2016 ">version 8.3.2</td>
    <td title="None">None</td>
  </tr>
</table>

@ Gurvinder建议将日期移至data。这是更理想和可扩展的方法

window.onload = function() {
  var td = document.getElementsByTagName('td');
  for (var i = 0; i < td.length; i++) {
    var deployEdOn = td[i].getAttribute("data-deployed-on")? new Date(td[i].getAttribute("data-deployed-on")):undefined;
    if (deployEdOn)
      td[i].className = deployEdOn.getMonth() < 2 ? "red" : "blue";
  }
}
.red {
  background: red;
  color: white;
}
.blue {
  background: blue;
  color: white;
}
<table>
  <tr>
    <td 
        title="Deployed on :Wed Mar 25 2015 10:00:00 UTC| check performed on: Wed Feb 14 2015 23:34:00 UTC " 
        data-deployed-on="Wed Mar 25 2015 10:00:00 UTC">Version 4.0</td>
    <td 
        title="Deployed on :Mon Feb 15 06:05:05 UTC 2016 |check performed on: Mon Feb 15 06:05:05 UTC 2016 " 
        data-deployed-on="Mon Feb 15 06:05:05 UTC 2016">version 8.3.2</td>
    <td 
        title="None">None</td>
  </tr>
</table>

答案 1 :(得分:0)

感谢Rajesh&amp; Gurvinder。最后在你的帮助下,它就像这样解决了

0x56
0x36
0x01