javascript:TypeError:document.getElementById(“myTable”)为空 [英] javascript: TypeError: document.getElementById("myTable") is null

查看:174
本文介绍了javascript:TypeError:document.getElementById(“myTable”)为空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我收到以下错误:

TypeError: document.getElementById("myTable") is null


它进入一个永无止境的循环。

on document.write(document.getElementById("myTable").rows[i].innerHTML); It goes into a never ending loop.

有人可以告诉我我做错了什么吗?谢谢。

Can someone tell me on what i'm doing wrong? Thank you.

我的代码:

<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>


推荐答案

这是因为当你做 document.write 在第一次你清除dom并且没有更多的table元素的时候,当你执行 document.write 第二次然后 document.getElementById(myTable)提供 null 。所以浏览器停止脚本提供错误。

It is because when you do document.write in the loop in the first time you clear dom and there is no more table element, and when you do document.write in the second time then document.getElementById("myTable") provides null. So browser stops the script provide the error.

这篇关于javascript:TypeError:document.getElementById(“myTable”)为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆