我正在尝试使用功能更改表格单元格背景的颜色。该代码很简单,但是某种程度上却无法正常工作。你能帮忙
function changecolor() {
var t = document.getElementById("t1");
var cells = t.getElementsByTagName("td");
/*Now cells become array-like, with td tag elements
indexed*/
cells[0] = style.backgroundColor = "red";
/* I suspect the code above has the error because my js
seem to break here.*/
}
<table border="1" id="t1">
<tr>
<th>name</th>
<th>surname</th>
<th>age</th>
</tr>
<tr>
<td>Ray</td>
<td>Nkiwane</td>
<td>26</td>
</tr>
<tr>
<td>Eric</td>
<td>cartman</td>
<td>10</td>
</tr>
</table>
<button id="b1" onClick="changecolor()">
Change to red
</button>
当我在按钮内放置警报时,单击按钮时会显示该警报,确认按钮和功能已正确链接。但是,如果此警报在函数末尾,则不会显示,提示里面的代码有错误
答案 0 :(得分:2)
问题出在这里:
cells[0] = style.backgroundColor = "red";
这意味着您正在尝试为单元格[0] 上的元素分配一个名为 style 的对象。 如果要更改特定元素的样式属性,则需要这样做:
cells[0].style.backgroundColor = "red";
答案 1 :(得分:1)
function changecolor() {
var t = document.getElementById("t1");
var cells = t.getElementsByTagName("td");
/*Now cells become array-like, with td tag elements
indexed*/
cells[0].style.backgroundColor = "red";
}
更改行单元格[0] = style.backgroundColor =“ red”;到cells [0] .style.backgroundColor =“ red”;