无法将属性InnerHTML设置为null [英] Cannot set property InnerHTML of null
问题描述
我有一个简单的html页面,body标签中没有代码。
我想通过javascript在body标签中插入html。
I've a simple html page with no code in the body tag. I want to insert the html in the body tag through javascript.
我的javascript文件看起来像这样。
My javascript file looks like this.
var Global={
UserWall:function(){
return "a very long html code";
}
};
var globalObject=Object.create(Global);
document.getElementsByTagName("body").item(0).innerHTML=globalObject.UserWall();
现在我希望在页面加载时将这个非常长的html代码自动插入到body标签中。
但它给了我在标题中提到的错误。为什么?
Now I want this very long html code to be auto inserted in the body tag on page load. But it is giving me the error I've mentioned in the title.Why?
这也是创建基于ajax的网站的正确方法(不页面重新加载)意味着如果我调用服务器端脚本来更新这个非常长的html代码并将其附加到页面正文。
and also is this the correct way to create ajax based website(no page reloads) meaning that if I called server side script to update this very long html code and appended it to the body of the page.
推荐答案
在构建DOM之前,您几乎肯定会运行代码。尝试在 window.onload
中运行代码处理函数(但请参阅下面的注释):
You are almost certainly running your code before the DOM is constructed. Try running your code in a window.onload
handler function (but see note below):
window.onload = function() {
// all of your code goes in here
// it runs after the DOM is built
}
另一种流行的跨浏览器解决方案是在结束< / body>
< script> 块>标签。根据您的需要,这可能是最佳解决方案:
Another popular cross-browser solution is to put your <script>
block just before the closing </body>
tag. This could be the best solution for you, depending on your needs:
<html>
<body>
<!-- all of your HTML goes here... -->
<script>
// code in this final script element can use all of the DOM
</script>
</body>
</html>
- 请注意
window.onload
将等到所有图像和子帧都已加载,这可能需要很长时间才能构建DOM。您还可以使用document.addEventListener(DOMContentLoaded,function(){...})
来避免此问题,但跨浏览器不支持此功能。底部技巧是跨浏览器并在DOM完成后立即运行。 - Note that
window.onload
will wait until all images and subframes have loaded, which might be a long time after the DOM is built. You could also usedocument.addEventListener("DOMContentLoaded", function(){...})
to avoid this problem, but this is not supported cross-browser. The bottom-of-body trick is both cross-browser and runs as soon as the DOM is complete.
这篇关于无法将属性InnerHTML设置为null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!