简体   繁体   English

根据单元格内容更改单元格颜色

[英]Change a cell colour based on cell content

I have some basic JavaScript code to scan the cells of an HTML table, and change the background colour based on an exact value, eg if the cell value is 5, then change the color to red, and this works fine : 我有一些基本的JavaScript代码来扫描HTML表格的单元格,并根据确切的值更改背景颜色,例如,如果单元格值为5,则将颜色更改为红色,这样就可以正常工作:

var cells = document.getElementById("test").getElementsByTagName("td");
for (var i = 0; i < cells.length; i++) {
if (cells[i].innerHTML == "5") {
    cells[i].style.backgroundColor = "red";
    }   
}

Typical table content : 典型表内容:

Now, my table cells actually all contain [present/absent] figures, in the format of eg 2/0 (2 present, 0 absent), and 2/1 (2 present, 1 absent). 现在,我的表格单元格实际上全部包含[当前/不存在]数字,格式为例如2/0(2个存在,0不存在)和2/1(2个存在,1不存在)。

I am trying to highlight the cells where the figure after the '/' is greater than 0, in other words, highlight only the cells where there are absences. 我正在尝试突出显示“ /”后面的数字大于0的单元格,换句话说,仅突出显示缺少的单元格。

I am struggling to find a way to actually do this, as I'm completely new to JavaScript. 由于我对JavaScript完全陌生,因此我正在努力寻找一种实现此目的的方法。 Any help would be appreciated! 任何帮助,将不胜感激!

Thank you. 谢谢。

You can split the innerHTML by / and check if its bigger than 0: 您可以通过/分割innerHTML并检查其是否大于0:

if (cells[i].innerHTML.split("/")[1] > 0) {
    cells[i].style.backgroundColor = "red";   
}

Not that this will throw an error if one of your cells doesn't contain a / , so you should add a check for that first. 如果您的单元格中不包含/ ,则不会引发错误,因此您应该首先添加一个检查。

var splitted = cells[i].innerHTML.split("/");
if (splitted.length > 1 && splitted[1] > 0) {
    // ...
}

Without seeing your HTML (at the time of writing) the best I can offer is the following: 在撰写本文时,没有看到您的HTML,我能提供的最好的是:

// retrieve all the <td> elements within a <table>
// Use a more specific selector than 'table', such
// as a class-name or id if you have multiple <table>
// elements:
var tableCells = document.querySelectorAll('table td'),

    // converts the collection of <td> elements into
    // an Array, using Array.from():
    tableCellsArray = Array.from( tableCells ),

    // finds a sequence of one or more (+) number (\d)
    // characters following a slash (\/):
    reg = /\/\d+/,

    // 'empty' variable for use within the
    // (later) Array.prototype.forEach():
    number;

// iterating over each of the <td> elements in the
// array we created earlier using Array.prototype.forEach():
tableCellsArray.forEach(function(cell){
  // 'cell': a reference to the current <td> in the
  // array of <td> elements over which we're iterating.

  // here we use String.prototype.match()
  // to recover the matching number(s), if any,
  // from the text-content of the <td>:
  number = cell.textContent.match(reg);

  // if no match then number will be equal to null,
  // so we first test that there is a match and
  // if there is we convert the found number into
  // a base-10 number using parseInt() and test if
  // that found number is greater than zero:
  if (number && parseInt(number[1], 10) > 0) {

    // if both the above are true, then here we
    // use the Element.classList API to add the
    // 'hasAbsences' class to the current <td>
    // element:
    cell.classList.add('hasAbsences');
  }
});

And specify the .hasAbsences class in the CSS. 并在CSS中指定.hasAbsences类。

 var tableCells = document.querySelectorAll('table td'), tableCellsArray = Array.from(tableCells), reg = /\\/(\\d+)/, number; tableCellsArray.forEach(function(cell) { number = cell.textContent.match(reg); if (number && parseInt(number[1], 10) > 0) { cell.classList.add('hasAbsences'); } }); 
 table { border-collapse: collapse; } td { border: 1px solid #000; padding: 0.2em 0.5em; text-align: center; } td.hasAbsences { background-color: red; } 
 <table> <tbody> <tr> <td>1/2</td> <td>2/0</td> <td>3/0</td> <td>4/0</td> <td>5/1</td> </tr> <tr> <td>1/0</td> <td>2/0</td> <td>3/-1</td> <td>4/0</td> <td>5/0</td> </tr> <tr> <td>1/0</td> <td>2/2</td> <td>3/0</td> <td>4/6</td> <td>5/0</td> </tr> </tbody> </table> 

JS Fiddle demo . JS小提琴演示

Does it only contains numbers? 它仅包含数字吗?

One way to do it is with parseInt the innerHTML: 一种方法是使用parseInt innerHTML:

 var cells = document.getElementById("test").getElementsByTagName("td"); for (var i = 0; i < cells.length; i++) { if (parseInt(cells[i].innerHTML.split('/')[1]) > 0) { cells[i].style.backgroundColor = "red"; } } 
 <table id="test"> <tr> <td> 0/0 </td> <td> 1/0 </td> <td> 2/1 </td> </tr> </table> 

EDIT: Got the question wrong edited.. 编辑:得到错误的问题编辑。

Please Try this one. 请试试这个。

var cells = document.getElementById("test").getElementsByTagName("td");
for (var i = 0; i < cells.length; i++) {
if (cells[i].innerHTML.indexOf('/') > -1 && parseInt(cells[i].innerHTML.split("/")[1]) > 0) {
    cells[i].style.backgroundColor = "red";
    }   
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM