如何有条件地格式化HTML表?

时间:2019-03-07 04:12:21

标签: javascript html arrays string

<td Class='metric' title='Test gave a performance metric.' lastPassTag=''>1997.0</td>
<td Class='metric' title='Test gave a performance metric.' lastPassTag=''>1997.0</td>
<td Class='metric' title='Test gave a performance metric.' lastPassTag=''>1997.0</td>
<td Class='metric' title='Test gave a performance metric.' lastPassTag=''>1997.0</td>
</tr><tr class='detail-hide'><td Class='result-name '>pmu: COMMITTED_PKT_BSB</td>
<td Class='metric' title='Test gave a performance metric.' lastPassTag=''>1655.0</td>
<td Class='metric' title='Test gave a performance metric.' lastPassTag=''>1836.0</td>
<td Class='metric' title='Test gave a performance metric.' lastPassTag=''>1655.0</td>
<td Class='metric' title='Test gave a performance metric.' lastPassTag=''>1836.0</td>

我有一个像上面的HTML表格 我正在尝试根据应用于那里的数字的公式进行条件格式化 我尝试过:

var tb = document.getElementByClass('metric')

我无法获得这些值 任何修改或建议,不胜感激 谢谢

3 个答案:

答案 0 :(得分:5)

代码的唯一问题是您使用错误的js上下文来使用js搜索类。

document.getElementByClass('metric')

因为类可以大于1,所以选择类的上下文是元素而不是下面的元素

document.getElementsByClass('metric')

希望这会解决您的查询。

如果需要其他帮助,请在此处评论,我会尽力解决

答案 1 :(得分:2)

该方法有误-您要使用document.getElementsByClassName

var tb = document.getElementByClass("metric");

您还可以使用querySelectorAll仅获得td类的metric元素:

var tb = document.querySelectorAll("td.metric");

答案 2 :(得分:1)

有两个问题:

1)您错过了第一个<tr>和最后一个</tr>,并且还必须将tr包裹在table标签中。

2) 更改:

document.getElementByClass('metric') ;    

收件人:

document.getElementsByClassName('metric') ;

var tb = document.getElementsByClassName('metric') ;

console.log(tb) ;
<table>
<tr>
  <td class='metric' title='Test gave a performance metric.' lastPassTag=''>1997.0</td>
  <td Class='metric' title='Test gave a performance metric.' lastPassTag=''>1997.0</td>
  <td Class='metric' title='Test gave a performance metric.' lastPassTag=''>1997.0</td>
  <td Class='metric' title='Test gave a performance metric.' lastPassTag=''>1997.0</td>
</tr>
<tr class='detail-hide'><td Class='result-name '>pmu: COMMITTED_PKT_BSB</td>
  <td Class='metric' title='Test gave a performance metric.' lastPassTag=''>1655.0</td>
  <td Class='metric' title='Test gave a performance metric.' lastPassTag=''>1836.0</td>
  <td Class='metric' title='Test gave a performance metric.' lastPassTag=''>1655.0</td>
  <td Class='metric' title='Test gave a performance metric.' lastPassTag=''>1836.0</td>
</tr>
</table>

相关问题