为什么 document.GetElementById 返回 null
我一直在成功使用 document.GetElementById()
,但从一段时间以来我无法让它再次工作。 看下面的代码:
<html>
<head>
<title>no title</title>
<script type="text/javascript">
document.getElementById("ThisWillBeNull").innerHTML = "Why is this null?";
</script>
</head>
<body>
<div id="ThisWillBeNull"></div>
</body>
</html>
我现在一直得到 document.getElementById("parsedOutput") is null
。 无论我使用 Firefox 还是 Chrome,或者我启用了哪些扩展,或者我为 HTML 使用什么标头,它总是 null
并且我找不到可能出现的问题。
I've been using document.GetElementById()
successfully but from some time on I can't make it work again.
look at the following Code:
<html>
<head>
<title>no title</title>
<script type="text/javascript">
document.getElementById("ThisWillBeNull").innerHTML = "Why is this null?";
</script>
</head>
<body>
<div id="ThisWillBeNull"></div>
</body>
</html>
I am getting document.getElementById("parsedOutput") is null
all the time now.
It doesn't matter if I use Firefox or Chrome, or which extensions I have enabled, or what headers I use for the HTML, it's always null
and I can't find what could be wrong.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
您可以像这样使用 script 标签:
加载所有内容后,JavaScript 将应用于所有元素。
You can use the script tag like this:
The JavaScript will apply to all elements after everything is loaded.
试试这个:
Try this:
如果没有window.onload,您的脚本永远不会被调用。 Javascript 是一种基于事件的语言,因此如果没有像 onload、onclick、onmouseover 这样的显式事件,脚本就不会运行。
加载事件:
https://developer.mozilla.org/en/DOM/window.onload
Without window.onload your script is never invoked. Javascript is an event based language so without an explicit event like onload, onclick, onmouseover, the scripts are not run.
Onload event:
https://developer.mozilla.org/en/DOM/window.onload
定时。
当您获取元素时,文档尚未准备好。
在检索元素之前,您必须等待文档准备就绪。
Timing.
The document isn't ready, when you're getting the element.
You have to wait until the document is ready, before retrieving the element.
浏览器一找到该脚本就会立即执行该脚本。此时,文档的其余部分尚未加载 - 还没有任何具有该 id 的元素。如果您在加载文档的该部分之后运行该代码,它将正常工作。
The browser is going to execute that script as soon as it finds it. At that point, the rest of the document hasn't loaded yet — there isn't any element with that id yet. If you run that code after that part of the document is loaded, it will work fine.
使用
+=
为文档的onload事件分配更多的eventHandler
。Use
+=
to assign moreeventHandler
s to onload event of document.