document.getElementById 抛出 TypeError
2011-07-12
4090
我对 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") 为 null
2. Dragonfly ->
未捕获异常:TypeError:无法将“document.getElementById("1")”转换为对象
在 hrefvalue() 的第 8 行第 0 列处抛出错误
file://localhost/D:/Chicago%20pics/website%20pics/website%20root/trial5.htm:
var newnew21 = document.getElementById("1").childNodes[0].getAttribute("href");
从 (event) 中的第 1 行第 0 列调用:
hrefvalue()
再次感谢大家的支持 :D
1个回答
- id 不能以数字开头(在 HTML 4 中)。不要指望浏览器支持此类 id。
-
document.write
将丢弃未 打开 的文档。当浏览器解析</html>
时,文档已关闭。由于该函数运行onclick
,因此它将在您尝试写入之前关闭。使用 DOM 方法 用 JS 修改 HTML。
Quentin
2011-07-12