仅当第四个单元格中的文本内容等于“ DELAYED”时,我才想修改表中每一行的颜色 我做了一个功能来做到这一点,但没有颜色改变...
function assignColor()
{
//getting all the tr elements from document
var x = document.getElementsByTagName("tr");
for(var i = 0; i < x.length; i++)
{
//Accessing to text Content in the 4th cell of the tr
if(x[i].cells[3].textContent == "DELAYED")
{
x[i].style.backgroundColor = "red";
}
}
}
我认为将表格从js填充到html的方式有问题
function printFlights(arrayOfFlight)
{
//I insert tr till the length of an array
for(var i = 0; i < arrayOfFlight.length; i++)
{
//creating tr element
var tr = document.createElement("tr");
//Inserting cells inside tr using propertys of an object
tr.insertCell(0).innerHTML =
formatDate(arrayOfFlight[i].arrivalDate);
tr.insertCell(1).innerHTML =
formatTime(arrayOfFlight[i].arrivalDate);
tr.insertCell(2).innerHTML = arrayOfFlight[i].destination;
tr.insertCell(3).innerHTML = arrayOfFlight[i].status;
tr.insertCell(4).innerHTML = arrayOfFlight[i].airplane;
tr.insertCell(5).innerHTML = arrayOfFlight[i].gate;
//add tr to tbody
tableBody.appendChild(tr);
}
}
答案 0 :(得分:0)
您的代码正在运行:
function assignColor()
{
//getting all the tr elements from document
var x = document.getElementsByTagName("tr");
for(var i = 0; i < x.length; i++)
{
//Accessing to text Content in the 4th cell of the tr
if(x[i].cells[3].textContent == "DELAYED")
{
x[i].style.backgroundColor = "red";
}
}
}
assignColor();
<table>
<tr>
<td>a</td>
<td>a</td>
<td>c</td>
<td>DELAYED</td>
</tr>
</table>
答案 1 :(得分:0)
您的代码似乎可以正常工作,但有一个例外-如果HTML中的<td>
元素中包含空格(例如下面的演示),则您的代码需要.trim()
的内容字符串比较之前的单元格。
参见下文:
function assignColor() {
var x = document.getElementsByTagName("tr");
for (var i = 0; i < x.length; i++) {
if (x[i].cells[3].textContent.trim() == "DELAYED") {
x[i].style.backgroundColor = "red";
}
}
}
assignColor();
<table border="1">
<tr>
<td>
Col 1
</td>
<td>
Col 2
</td>
<td>
Col 3
</td>
<td>
Col 4
</td>
</tr>
<tr>
<td>
Col 1
</td>
<td>
Col 2
</td>
<td>
Col 3
</td>
<td>
DELAYED
</td>
</tr>
答案 2 :(得分:-1)
以这种方式尝试,无论单元号如何,它都会检查“已延迟”。
function assignColor() {
var x = document.querySelectorAll('tr td');
for(var i = 0; i < x.length; i++) {
if(x[i].textContent == "DELAYED") {
x[i].style.backgroundColor = "red";
}
}
}
<table>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
<td>DELAYED</td>
</tr>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
<td>DELAYED</td>
</tr>
<tr>
<td>1</td>
<td>2</td>
<td>DELAYED</td>
<td>4</td>
</tr>
</table>