为什么 DOM 元素为空? [英] Why is a DOM element null?

查看:53
本文介绍了为什么 DOM 元素为空?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个简单的 HTML 文件:

I have this simple HTML file:

<!DOCTYPE html>
<html>
<head>
    <script src='test.js'></script>
</head>

<body>
    <p>I am a paragraph tag</p>
    <h1 >I am an h1 tag</h1>
    <div id="id"> I am a div tag</div>
</body>

还有这个简单的脚本(test.js):

And this simple script (test.js):

y=document.getElementById("id");
y.style.color="green";

到底为什么y"为空?我得到的错误是

Why on earth is "y" null? The error I'm getting is

TypeError: y is null

我确定这是我遗漏的简单语法,但我终生无法弄清楚!帮助!

I'm sure this is a simple syntax thing that I'm missing, but I can't for the life of me figure it out! Help!

发布脚本:html文件和test.js文件在同一个文件夹中.

Post Script: Both the html file and the test.js file are in the same folder.

推荐答案

当所有元素都被创建时,你必须把脚本放在文档的末尾:

you have to place the script at the end of the document when all the elements are created:

<!DOCTYPE html>
<html>
<head>

</head>

<body>
    <p>I am a paragraph tag</p>
    <h1 >I am an h1 tag</h1>
    <div id="id"> I am a div tag</div>
</body>
<script src='test.js'></script>

这篇关于为什么 DOM 元素为空?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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