Javascript getElementById null错误 [英] Javascript getElementById null error

查看:87
本文介绍了Javascript getElementById null错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近发布了关于firefox中javascript的一个问题,并且表示问题很可能是document.write()以某种方式覆盖了脚本。 有人建议我使用ID来解决覆盖脚本和避免堆叠信息的问题

I posted quite recently about an issue with javascript in firefox, and it was denoted the problem was likely document.write() overwriting the script somehow. It was suggested I use IDs to solve the problem of both overwriting the script and to avoid stacking of the information.

然而,在尝试将ID实现到我的javascript和html代码中时,我发现firebug报告:

However, on trying to implement the IDs into my javascript and html code, I found that firebug reports that:

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

尽管事实如此,ID已经在以下定义:

Despite the fact, that, once again, the ID is already defined under:

<p id="author_container"></p>

并且显然没有拼写错误,并重新安排脚本头部分或改变它所以p发生在脚本完全没有区别之前。 (注意,尽管首先出现了脚本,但另一个示例运行正常。)

And there are clearly no typos, and re-arranging the script into the head section or altering it so the p occurs before the script makes absolutely no difference. (Note the other example runs fine despite the script occurring first).

如果我使用预先存在的ID和getElementById示例并在firefox中运行它,它会运行罚款:

If I use a pre-existing example of an ID and getElementById and run it in firefox, it runs fine:

http://pastebin.com/FTEX1HGE

但如果我尝试运行我的代码,这似乎没有什么大不相同,我遇到了问题:
http://pastebin.com/XfGUpZAS

But if I try to run my code, which doesn't seem that majorly different, I run into issues: http://pastebin.com/XfGUpZAS

我在这里遗漏了什么吗?如何更改代码以使其在Firefox中运行? firefox是否允许我正确运行我的代码? (下周查找?)

Am I missing something here? How do I alter the code to make it work in firefox? Will firefox allow me to ever run my code correctly? (Find out next week?)

推荐答案

将您的脚本放在页面底部,就在结束<$ c $之前c>< / body> 标记。换句话说,使脚本标记成为 document.body 的最后一个。这样,在脚本开始之前就完全加载了DOM树。

Place your script at the bottom of the page, right before the closing </body> tag. In other words, make the script tag the last one of document.body. That way the DOM-tree is completely loaded before the scripting starts.

除了许多问题之外,真正的问题是 document.open GenerateCoord 函数中的语句。 清除完整的文档,之后 - 确实 - 没有任何元素可以通过任何Id获取。这是没有它的 jsfiddle

Aside from a number of issues, the real issue is the document.open statement in the GenerateCoord function. That clears the complete document, after which - indeed - no element is left to get by any Id. Here's a jsfiddle without it.

这篇关于Javascript getElementById null错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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