【发布时间】:2017-08-10 19:50:23
【问题描述】:
所以,我有一个带有文字的表格。表中有<th> 和<td>。在某些单元格上,根据单元格的文本,我希望背景更改某种颜色,如果某个特定单元格包含“+”号,我想更改颜色并删除“+”号。
这就是我所拥有的。当它到达一个空单元格并且“+”替换过于严格时,它会中断,即它只会在单元格中唯一的内容时删除“+”。如果是“8+”,则不会删除“+”号。
我是 Javascript 的新手。我相信这可以做得更简单。
<table>
<tr>
<th>SAT</th>
<th>SUN</th>
</tr>
<tr>
<td>K</td>
<td> </td>
<td>8+</td>
</tr>
</table>
<script type="text/javascript">
function isEmpty( el ){
return !$.trim(el.html())
}
var allTableCells = document.getElementsByTagName("td");
for(var i = 0, max = allTableCells.length; i < max; i++) {
var node = allTableCells[i];
//get the text from the first child node - which should be a text node
var currentText = node.childNodes[0].nodeValue;
//check for certain content and assign this table cell's background color accordingly
if (!isEmpty($(currentText))) {
if (currentText === "K")
node.style.backgroundColor = "#ffff00";
else if (currentText === "+")
node.style.backgroundColor = "#0070c0";node.childNodes[0].nodeValue = currentText.replace("+", " ");
}
}
var allTableHeaders = document.getElementsByTagName("th");
for(var ic = 0, max = allTableHeaders.length; ic < max; ic++) {
var node = allTableHeaders[ic];
//get the text from the first child node - which should be a text node
var currentHeadText = node.childNodes[0].nodeValue;
//check for certain days of the week and assign this table cell's background color accordingly
if (!isEmpty($(currentHeadText))) {
if (currentHeadText === "SAT")
node.style.backgroundColor = "#ff0000";
else if (currentHeadText === "SUN")
node.style.backgroundColor = "#91CF4F";
}
}
</script>
【问题讨论】:
标签: javascript jquery html html-table nodes