从document.getElementById获取文档未定义 [英] Getting document is not defined , from document.getElementById
问题描述
我正在学习JavaScript,并且正在使用Atom(文本编辑器). 在我的HTML文件中,只有这个:
I am learning JavaScript and I am using Atom (Text Editor). On my HTML file I got only this:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
<script src="script.js"></script>
</head>
<body>
<h1>Hello Plunker!</h1>
<button id="displayTodosButton">Display Todos</button>
<button>Toggle Todos</button>
</body>
</html>
在我的javascript文件上,我只是尝试使用以下方法访问显示待办事项"按钮:
On my javascript file, I am simply trying to access the "Display todos" button using this:
var displayTodosButton = document.getElementById('displayTodosButton')
我正在观看视频,并且讲师正在使用 plnkr.co ,他可以正常访问按钮,但在Atom上却收到"ReferenceError:未定义文档"
I was watching a video, and the instructor is using plnkr.co, and he accesses the button just fine, yet on Atom I get the "ReferenceError: document is not defined"
我该如何解决?
推荐答案
我还了解Atom
yet on Atom I get
如果您的确是文本编辑器Atom突出显示了该文本,并向您显示警告document
未定义,则只是Atom并未意识到您正在
If you really mean that Atom, your text editor, is highlighting it and showing you a warning that document
is undefined, it's just that Atom doesn't realize you're running that code in a browser context where document
will be defined.
它可能具有一个可以告诉您将在浏览器中运行代码的设置,因此它可以假定默认的全局集合(window
,document
等).
It probably has a setting where you can tell it that you'll be running the code in a browser, so it can assume the default set of globals (window
, document
, etc.).
如果script.js
中的代码正是您所显示的,尽管错误Atom显示您不会有问题(因为在浏览器中,document
不会是undefined
),但是您ll从getElementById
返回null
,因为您的代码在元素存在之前运行.再次,这是假定代码是自己的,而不是(例如)在DOMContentLoaded
处理程序或类似程序内.
If the code in script.js
is just what you've shown, although the error Atom is showing you won't be a problem (because in the browser, document
will not be undefined
), you'll get null
back from getElementById
because your code runs before the element exists. Again, this is assuming that code is on its own, not (say) inside a DOMContentLoaded
handler or similar.
除非您有充分的理由这样做(而且没有很多),否则将script
元素放在head
中是一种反模式.将其放在body
中,紧接在结束</body>
标记之前,放在最后.这样,在代码上方定义的所有元素都将在代码运行之前由浏览器创建.
Unless you have a good reason to do it (and there aren't many), putting script
elements in the head
is an anti-pattern. Put them in body
, right at the end, just prior to the closing </body>
tag. That way, any elements defined above them will have been created by the browser before your code runs.
这篇关于从document.getElementById获取文档未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!