Table .cells将返回table中的所有内部单元格。在IE中可以正常工作。但是在Chrome浏览器中,.cells将返回“ undefined”,因为不存在此类属性。我们必须遍历每一行以查找单元格。是否还有其他方法可以将所有单元格都保存为chrome?>
function myFunction() {
var x = document.getElementById("myTable").cells.length;
document.getElementById("demo").innerHTML = "Found " + x + " cells in
the first tr element.";
}
<table id="myTable">
<tr>
<td>cell 1</td>
<td>cell 2</td>
</tr>
<tr>
<td>cell 3</td>
<td>cell 4</td>
</tr>
</table>
答案 0 :(得分:0)
没有什么叫document.getElementById("myTable").cells.length
.cells
实际上什么也不返回,因此您的x
变量返回undefined并且您没有得到单元格编号。
相反,您可以执行以下操作:
function myFunction() {
var x = document.getElementById("myTable");
// if you need all the cells which is td elements
var cells = x.getElementsByTagName('td');
// if you need only cells in a single row which is a tr element
var cellsPerRow = x.getElementsByTagName('tr')[0].getElementsByTagName('td');
document.getElementById("demo").innerHTML = "Found " + cellsPerRow.length + " cells in the first tr element." + "And " + cells.length + " cells in total" ;
}
myFunction();
<table id="myTable">
<tr>
<td>cell 1</td>
<td>cell 2</td>
</tr>
<tr>
<td>cell 3</td>
<td>cell 4</td>
</tr>
</table>
<div id='demo'></div>