无法读取null`的属性'style',但在jsFiddle中工作正常

时间:2022-11-20 21:19:48

I'm trying to make a very basic game in with JS, my code works fine(ish) in jsfiddle, it doesnt work when im putting it all into my HTML and JS documents however - i keep getting the same error when debugging: Uncaught TypeError: Cannot read property 'style' of null at line 11 stating bigThing.style.left = "10px";

我正在尝试使用JS制作一个非常基本的游戏,我的代码在jsfiddle中运行良好(ish),当我将它全部放入我的HTML和JS文档时它不起作用但是 - 我在调试时不断收到相同的错误:未捕获TypeError:无法在第11行读取属性'style'为null,说明bigThing.style.left =“10px”;

First noobie question here, hope anybody can help me figure out why it doesn't work to just copy-paste this into an html document.

这里的第一个noobie问题,希望任何人都可以帮我弄清楚为什么它只是将它复制粘贴到html文档中不起作用。

JsFiddle link here`

JsFiddle链接在这里`

Thank you for your time.

感谢您的时间。

2 个解决方案

#1


You need to wrap the entire thing inside of a:

你需要把整个东西包裹在一个:

window.onload = function(){
   //You code here
}

The problem can arise when you have your script loading and executing prior to the DOM being parsed. One other alternative is to place your scripts immediately prior to the closing </body> tag.

当您在解析DOM之前加载并执行脚本时,可能会出现此问题。另一种方法是在结束 标记之前放置脚本。

#2


Your problem is quite straight forward. Your HTML file is parsed top-down as it is an interpreted script. I am going to assume you import your JS script inside your head tags. The JS is trying to access the DOM before it is fully loaded, this causes the error to be thrown. Make it so your JS script import is called after all of the content in the body of your HTML file. Your markup will load, then JS will access it, and all should be good.

你的问题很简单。您的HTML文件是自上而下解析的,因为它是一个解释的脚本。我假设您在头标记中导入JS脚本。 JS在完全加载之前尝试访问DOM,这会导致抛出错误。这样就可以在HTML文件正文中的所有内容之后调用JS脚本导入。您的标记将加载,然后JS将访问它,一切都应该是好的。

#1


You need to wrap the entire thing inside of a:

你需要把整个东西包裹在一个:

window.onload = function(){
   //You code here
}

The problem can arise when you have your script loading and executing prior to the DOM being parsed. One other alternative is to place your scripts immediately prior to the closing </body> tag.

当您在解析DOM之前加载并执行脚本时,可能会出现此问题。另一种方法是在结束 标记之前放置脚本。

#2


Your problem is quite straight forward. Your HTML file is parsed top-down as it is an interpreted script. I am going to assume you import your JS script inside your head tags. The JS is trying to access the DOM before it is fully loaded, this causes the error to be thrown. Make it so your JS script import is called after all of the content in the body of your HTML file. Your markup will load, then JS will access it, and all should be good.

你的问题很简单。您的HTML文件是自上而下解析的,因为它是一个解释的脚本。我假设您在头标记中导入JS脚本。 JS在完全加载之前尝试访问DOM,这会导致抛出错误。这样就可以在HTML文件正文中的所有内容之后调用JS脚本导入。您的标记将加载,然后JS将访问它,一切都应该是好的。