Javascript错误 - 无法调用null的方法'appendChild' [英] Javascript error - cannot call method 'appendChild' of null

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

问题描述

我是Javascript(以及一般编程)的新手,并且一直在努力掌握使用DOM的基本知识。如果这是一个非常基本的错误,请道歉,但我环顾四周,找不到答案。

I am new to Javascript (and programming in general) and have been trying to get a basic grasp on working with the DOM. Apologies if this is a very basic mistake, but I looked around and couldn't find an answer.

我正在尝试使用appendChild方法将标题和一些段落文本添加到下面的基本HTML文件中。

I am trying to use the appendChild method to add a heading and some paragraph text into the in the very basic HTML file below.

    <html> 
<head>
    <title>JS Practice</title>  
</head>
<body>
    <script src="script.js"></script> 
    <div id = "main">
        <h1>Simple HTML Page</h1>
        <p>This is a very simple HTML page.</p>
        <p>It's about as basic as they come. It has: </p>
        <ul>
            <li>An H1 Tag</li>
            <li>Two paragraphs</li>
            <li>An unordered list</li>
        </ul>
    </div>
    <div id="javascript">
    </div>
</body>
</html>

这是js代码:

var newHeading = document.createElement("h1"); 
var newParagraph = document.createElement("p"); 

newHeading.innerHTML = "New Heading!"; 
newParagraph.innerHTML = "Some text for a paragraph."; 

document.getElementById("javascript").appendChild(newHeading); 
document.getElementById("javascript").appendChild(newParagraph); 

运行它会导致错误:无法调用方法'appendChild'为null

Running it causes an error: "Cannot call method 'appendChild' of null"

帮助?我无法弄清楚为什么这不起作用...

Help? I can't figure out why this isn't working...

推荐答案

假设此代码在<$ c $内c> script.js 文件,这是因为在加载HTML页面的其余部分之前javascript正在运行。

Assuming this code is inside the script.js file, this is because the javascript is running before the rest of the HTML page has loaded.

当HTML页面加载时,当它遇到链接资源(如javascript文件)时,它会加载该资源,执行它可以执行的所有代码,然后继续运行页。因此,在页面上加载< div> 之前,您的代码正在运行。

When an HTML page loads, when it comes across a linked resource such as a javascript file, it loads that resource, executes all code it can, and then continues running the page. So your code is running before the <div> is loaded on the page.

< script> 标记移至页面底部,您不应再出现错误。或者,引入一个事件,例如< body onload =doSomething();> 然后制作 doSomething()方法将运行这些语句。

Move your <script> tag to the bottom of the page and you should no longer have the error. Alternatively, introduce an event such as <body onload="doSomething();"> and then make a doSomething() method in your javascript file which will run those statements.

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

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