<table border="1" width="50%" id="table"> <tr> <th>学号</th> <th>姓名</th> <th>操作</th> </tr> <tr> <td>xh001</td> <td>阮雌</td> <td><a href="javascript:;" onclick="delete(this)">删除</a></td> <!--在删除按钮上添加点击事件 --> </tr> <tr> <td>xh002</td> <td>刘赫</td> <td><a href="javascript:;" onclick="delete(this)" >删除</a></td> <!--在删除按钮上添加点击事件 --> </tr> </table> <input type="button" value="添加一行" onclick="add()" /> <!--在添加按钮上添加点击事件 --> <script> window.onload = function(){ var tr=document.getElementsByTagName("tr"); var td=document.getElementsByTagName("td"); for(var i=0;i<tr.length;i++){ var n=1; n++; var k=0; while(k<cells.length){ k++; } let cells=tr[i+n].cells; // tr[i+n].cells.innerHTML+="xh00"; console.log(tr[i+n].cells.length) } } 报错:没找到length元素,判断下cells是否为underfined或者为空,如是则不遍历,就不会js报错了。 正确改为: window.onload = function(){ var tr=document.getElementsByTagName("tr"); var td=document.getElementsByTagName("td"); for(var i=0;i<tr.length;i++){ var n=1; n++; var k=0; while(k<tr[i+n].cells.length){ k++; } let cells=tr[i+n].cells; // tr[i+n].cells.innerHTML+="xh00"; console.log(tr[i+n].cells.length) } }
</script>
报错: Uncaught TypeError: Cannot read property 'cells' of undefined,cells元素未定义,书写顺序错误,写在while之前,之后又报了个cell is not defined;
正确改为:
<script>
window.onload = function(){
var tr=document.getElementsByTagName("tr");
var td=document.getElementsByTagName("td");
for(var i=0;i<tr.length;i++){
var n=1;
n++;
let cells=tr[i+n].children;
for(var j=0; j<cells.length; j++){
console.log(cells[j])
}
var k=0;
while(k<tr[i+n].cells.length){
k++;
}
}
}
</script>