如何修复“未捕获的类型错误:无法调用 null 的方法 'appendChild'" [英] How to fix "Uncaught TypeError: Cannot call method 'appendChild' of null"
问题描述
我试图从 HTML 文本区域抓取文本,并在按下提交"按钮时调用 create() 方法.该方法试图使用来自文本区域的消息,并将其发布到自己的带有类的 p 标签,并在其自己的 p 标签和自己的类中发布日期戳.
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.
这些都将在 div 'comments' 中.我得到的错误(在 Chrome 中使用开发人员工具)是
These will both be in the div 'comments'. The error I am getting (using developer tools in Chrome), is
未捕获的类型错误:无法调用 null 的方法appendChild".
Uncaught TypeError: Cannot call method 'appendChild' of null.
这是针对cmt.appendChild(divTag);"的.我对 Javascript 很陌生,这只是我提高技能的练习.非常感谢所有帮助!
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!
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);
}
推荐答案
您收到的错误表明您的页面上没有 ID 为comments"的元素.document.getElementById
将返回null
当没有找到具有这样 ID 的元素时,因此 cmd.appendChild(divTag)
将作为 null.appendChild(divTag)
执行.
The error you are getting suggests that there is no element with the ID "comments" on your page. document.getElementById
will return null
when no element with such an ID is found, and thus cmd.appendChild(divTag)
will be executed as null.appendChild(divTag)
.
如果您确定该元素存在,则您可能正在执行您的 JavaScript,该 JavaScript 在浏览器创建该元素之前分配了 cmt
变量.为防止出现这种情况,标准做法是将包含外部 JavaScript 的 标签放在结束
</body>
标签之前>.
If you are certain that the element exists, you may be executing your JavaScript that assigns the cmt
variable 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.
如果由于某种原因您无法移动脚本标记,请尝试运行使用 $(document).ready()
(jQuery) 或等价物.
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.
这篇关于如何修复“未捕获的类型错误:无法调用 null 的方法 'appendChild'"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!