Javascript 如何修复“未捕获的类型错误:无法调用 null 的方法‘appendChild’”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14946428/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to fix "Uncaught TypeError: Cannot call method 'appendChild' of null"
提问by Fizzix
I am attempting to grab text from a HTML text area, and call the create() method when a 'Submit' button is pressed. The method is trying to use the message from the text area, and post that to its own p tag with class, and post a date stamp in its own p tag, and its own class.
我试图从 HTML 文本区域抓取文本,并在按下“提交”按钮时调用 create() 方法。该方法试图使用来自文本区域的消息,并将其发布到自己的带有类的 p 标签,并在其自己的 p 标签和自己的类中发布日期戳。
These will both be in the div 'comments'. The error I am getting (using developer tools in Chrome), is
这些都将在 div 'comments' 中。我得到的错误(在 Chrome 中使用开发人员工具)是
Uncaught TypeError: Cannot call method 'appendChild' of null.
未捕获的类型错误:无法调用 null 的方法“appendChild”。
This is aimed at "cmt.appendChild(divTag);". I am very new to Javascript, and this is just practise for me to increase my skills. All help is greatly appreciated!
这是针对“cmt.appendChild(divTag);”。我对 Javascript 很陌生,这只是我提高技能的练习。非常感谢所有帮助!
var cmt = document.getElementById('comments');
function create() {
var username = 'User',
message = document.getElementById("textBox").value,
divTag = document.createElement('div'),
p1 = document.createElement('p'),
p2 = document.createElement('p');
divTag.className = 'comment';
p1.className = 'date';
p1.innerHTML = new Date();
divTag.appendChild(p1);
p2.className = 'message';
p2.innerHTML = username + ': ' +message;
divTag.appendChild(p2);
cmt.appendChild(divTag);
}
回答by fresskoma
The error you are getting suggests that there is no element with the ID "comments" on your page. document.getElementByIdwill return nullwhen no element with such an ID is found, and thus cmd.appendChild(divTag)will be executed as null.appendChild(divTag).
您收到的错误表明您的页面上没有 ID 为“评论”的元素。当没有找到具有此类 ID 的元素时document.getElementById将返回null,因此cmd.appendChild(divTag)将作为null.appendChild(divTag).
If you are certain that the element exists, you may be executing your JavaScript that assigns the cmtvariable before that element is created by the browser. To prevent that, standard practice is to place the <script>tag which includes your external JavaScript just before the closing </body>tag.
如果您确定该元素存在,您可能正在执行 JavaScript,在浏览器创建该元素之前分配cmt变量。为了防止这种情况,标准做法是将包含外部 JavaScript的标签放在结束标签之前。<script></body>
If you can't move your script tag for some reason, try running the code that assigns the variable with $(document).ready()(jQuery) or equivalent.
如果由于某种原因无法移动脚本标记,请尝试运行使用$(document).ready()(jQuery)或等效项分配变量的代码。
回答by Nope
Your code works if the required elements exist. As you can see in this Fiddle.
如果所需元素存在,您的代码就可以工作。正如你在这个 Fiddle 中看到的。
Works if HTML is similar to:
如果 HTML 类似于:
<div id="comments">
<input id="textBox" type="textBox" value="Hello" />
</div>
My guess is that one of the identifiers might be misspelled or the element as you expect it does not exist.
我的猜测是其中一个标识符可能拼写错误,或者您期望的元素不存在。
However, if you are running the script in an external file it might try to execute before the document is fully loaded, hence your script is referring to elements not yetready in the DOM.
但是,如果您在外部文件中运行脚本,它可能会在文档完全加载之前尝试执行,因此您的脚本指的是 DOM 中尚未准备好的元素。
In jQuery you would wrap a $(document).ready(function(){// your code here..})around.
There is some details on how to do this in just JavaScript in this SO post: Documen Ready equivalent without jQuery.
在 jQuery 中,你会环绕一个$(document).ready(function(){// your code here..})。
在这篇 SO 帖子中,有一些关于如何在 JavaScript 中执行此操作的详细信息:Documen Ready 等效,没有 jQuery。
回答by Brendan
Actually, his code is fine. Its just that JavaScript runs BEFORE HTML. A simple fix is to nest all of your code inside of a function with any name. Then use window.onload to run the function after the HTML is loaded. so basically:
实际上,他的代码很好。只是 JavaScript 在 HTML 之前运行。一个简单的解决方法是将所有代码嵌套在具有任何名称的函数中。然后在加载完 HTML 后使用 window.onload 运行该函数。所以基本上:
window.onload = function any_name()
{
//code to be executed
}
This is useful especially if you do not want to move your script tag. I generally like to leave the tag where it is.
这在您不想移动脚本标记时尤其有用。我通常喜欢将标签留在原处。

