我收到以下错误:
TypeError: document.getElementById("myTable") is null
on document.write(document.getElementById(“myTable”)。rows [i] .innerHTML); 它进入了一个永无止境的循环。
有人可以告诉我我做错了什么吗?谢谢。
我的代码:
<script type="text/javascript">
function colorRows(){
count=document.getElementById("myTable").rows.length;
alert("count is:"+count);
for (i=0;i<=count;i++){
if (i%2===0){
document.write(document.getElementById("myTable").rows[i].innerHTML);
}
}
}
</script>
</head>
<body>
<table id="myTable">
<tr>
<th>emp_id</th>
<th>name</th>
<th>age</th>
</tr>
<tr>
<td>1</td>
<td>vaani</td>
<td>35</td>
</tr>
<tr>
<td>2</td>
<td>Ramu</td>
<td>37</td>
</tr>
<tr>
<td>3</td>
<td>Iniyan</td>
<td>5</td>
</tr>
<tr>
<td>4</td>
<td>Mickey</td>
<td>10</td>
</tr>
</table>
<form method="post" action="JavaScript:colorRows();">
<input type="submit" value="Submit" />
</form>
</body>
</html>
答案 0 :(得分:1)
这是因为当您第一次在循环中执行document.write
时清除dom并且没有更多的表元素,并且当您第二次执行document.write
时document.getElementById("myTable")
提供null
。因此浏览器会停止脚本提供错误。
答案 1 :(得分:0)
运行代码时出现同样的错误。 我把myTable放到了一个新的变量之外。它工作正常。那样的。
var myTableVar = document.getElementById("myTable");
var i;
for (i=0;i<=count;i++){
alert("i = " + i);
if (i%2===0){
document.write(myTableVar.rows[i].innerHTML);
}
}
完整代码:
<html>
<head>
<script type="text/javascript">
function colorRows(){
count=document.getElementById("myTable").rows.length;
alert("count is:" + count);
var myTableVar = document.getElementById("myTable");
var i;
for (i=0;i<=count;i++){
alert("i = " + i);
if (i%2===0){
document.write(myTableVar.rows[i].innerHTML);
}
}
}
</script>
</head>
<body>
<table id="myTable">
<tr>
<th>emp_id</th>
<th>name</th>
<th>age</th>
</tr>
<tr>
<td>1</td>
<td>vaani</td>
<td>35</td>
</tr>
<tr>
<td>2</td>
<td>Ramu</td>
<td>37</td>
</tr>
<tr>
<td>3</td>
<td>Iniyan</td>
<td>5</td>
</tr>
<tr>
<td>4</td>
<td>Mickey</td>
<td>10</td>
</tr>
</table>
<form method="post" action="JavaScript:colorRows();">
<input type="submit" value="Submit" />
</form>
</body>
</html>
答案 2 :(得分:0)
试试这个
function colorRows(){
var table = document.getElementById("myTable");
count=table.rows.length;
alert("count is:"+count);
for (i=0;i<=count;i++){
if (i%2===0){
document.write(table.rows[i].innerHTML);
}
}
}
最好只能访问一次表。 document.write()清除页面,因为它调用document.open()