【问题标题】:document.getElementById throws TypeErrordocument.getElementById 抛出 TypeError
【发布时间】:2011-10-03 11:00:24
【问题描述】:

我对 Javascript 有点陌生。我正在编写这个虚拟脚本来测试我的大页面需要什么。我想,最简单的是,获取 href 的值,然后更改 href 的值,然后再次查看它。为了简单起见,现在我已经删除了更改 href 值的部分,并且只调用了两次属性值。但是第二次访问属性值时,它显示了我在下面发布的错误。我发布了两份错误日志,一份来自 Firebug,一份来自 Dragonfly(来自 Opera)。

任何帮助将不胜感激。谢谢。

脚本的另一个问题是它永远无法完成加载。我总是在标签标题中看到(在 Firefox 3.6.8 中)小加载标志。它并没有给我带来太多困扰,但如果有人有想法请告诉我。

<!-- This file is used to set attribute value for href. -->
<html>
<head>

<script type="text/javascript">
   function hrefvalue()
{
var thisthang = document.getElementById("1").childNodes[0].getAttribute("href");
document.write(thisthang);
document.write("\n");

var newnew21 = document.getElementById("1").childNodes[0].getAttribute("href");
document.write(newnew21);
}
</script>

</head>

<body>

<div id="1"><a href="focusdude.htm">click here</a></div>
<button type="button" onclick="hrefvalue()">Click me instead</button>

</body>
</html>

错误日志:
1. Firebug -> document.getElementById("1") 为空

2. 蜻蜓 ->
未捕获的异常:TypeError: Cannot convert 'document.getElementById("1")' to object


中的 hrefvalue() 中的第 8 行第 0 列抛出错误 文件://localhost/D:/Chicago%20pics/website%20pics/website%20root/trial5.htm:
var newnew21 = document.getElementById("1").childNodes[0].getAttribute("href");
从(事件)中的第 1 行第 0 列调用: hrefvalue()

再次感谢所有的鱼:D

【问题讨论】:

    标签: javascript null getelementbyid typeerror


    【解决方案1】:
    1. id 不能以数字开头(在 HTML 4 中)。不要押注支持此类 ID 的浏览器。
    2. document.write 将删除未打开的文档。当浏览器解析&lt;/html&gt; 时,文档被关闭。由于该函数运行onclick,因此在您尝试编写之前将其关闭。使用DOM methods用JS修改HTML。

    【讨论】:

    • 那么为什么第一个有效?
      我得到了 document.write(thishang) 的输出,但没有得到 newnew21 的输出。
    • 因为在您调用document.write 第一次之前,您还没有销毁您尝试读取的元素之前
    • “ID 不能以数字开头” FWIW,曾经是真的in HTML4.01,现在仍然是真的@987654323 @,但是HTML5 now allows it。请注意,我不会将1 用作id。 (引用的页面根本没有指定任何文档类型,但是嘿。)
    • @Quentin:恰恰相反,我很确定规范在这种情况下捕捉到了实际情况。
    • @downvoter:为什么要投反对票? Quentin 指出了代码的关键问题(#2),并警告用户不要采取可能会在某个时候咬到他/她的做法(#1)。
    猜你喜欢
    • 2013-11-30
    • 2012-11-26
    • 1970-01-01
    • 2014-10-13
    • 1970-01-01
    • 2016-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多