我不知道为什么会出现此错误。一切都按预期工作,只是控制台抛出此错误。谁能确定原因?
无法获得未定义或空引用的属性“样式”
function openEditTable(tableid, DDid, ADid, Editid, UCid){
var table = document.getElementById(tableid);
var DDid = document.getElementById(DDid);
var ADid = document.getElementById(ADid);
var Editid = document.getElementById(Editid);
var UCid = document.getElementById(UCid);
for (var i = 0, row; row = table.rows[i]; i++) {
col = row.cells[8];
col.style.display = '';
DDid.style.display = 'none';
ADid.style.display = 'none';
Editid.style.display = 'none';
UCid.style.display = '';
}
}
答案 0 :(得分:0)
要获得预期结果,请使用以下选项查找列的位置并使用相同的索引来设置单元格的样式
示例工作代码以供参考
function openEditTable(tableid, colName){
var table = document.getElementById(tableid);
let index;
for (var i = 0, row; row = table.rows[i]; i++) {
for (var j = 0; j<row.cells.length; j++) {
if(row.cells[j].textContent ===colName){
index = j
}
if(row.cells && row.cells[index]){
row.cells[index].style.color = 'red';
}
}
}
}
openEditTable('tableid', 'Lastname')
table tr td{
border: 1px solid black
}
<table style="width:100%" id="tableid">
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Age</th>
</tr>
<tr>
<td>Jill</td>
<td>Smith</td>
<td>50</td>
</tr>
<tr>
<td>Eve</td>
<td>Jackson</td>
<td>94</td>
</tr>
</table>