![](/img/trans.png)
[英]JavaScript: Uncaught TypeError: Cannot read property 'length' of undefined at prac.js:13
[英]Uncaught TypeError: Cannot read property 'style' of null at prac.js:3
var hi = document.querySelector("h1");
hi.style.color = "red";
使用 DOM 為 h1 賦予顏色的這 2 行代碼給出了錯誤
未捕獲的類型錯誤:無法在 prac.js:3 處讀取 null 的屬性“樣式”
在單獨的 javascript 文件中寫入時,而相同的 2 行在控制台中可以正常工作並產生所需的效果。
HTML:
<!DOCTYPE html>
<html>
<head>
<title>Experiments</title>
<script src = "prac.js"></script>
</head>
<body>
<h1>Hey there!</h1>
</body>
</html>
這是該問題的演示:
var hi = document.querySelector("h1"); hi.style.color = "red";
由於不清楚您如何使用 JavaScript,因此很難確定實際問題。
但是,讓我們假設您僅在同一文件 HTML 中使用 JavaScript,那么您編寫的代碼工作正常,您可以查看下面的代碼片段。
<.DOCTYPE html> <html> <head> <title>Experiments</title> <script src = "prac.js"></script> </head> <body> <h1>Hey there;</h1> <script> var hi = document.querySelector("h1"). hi;style.color = "red"; </script> </body> </html>
Since mostly we are manipulating the DOM
using JavaScript, this is a good practice to have JavaScript load from another file(or if you are using Javascript on the same page)at the bottom of your HTML content, just before the </body>
tag ,直到那時大多數 HTML 內容都將被加載以供 DOM 使用。
如果您的 JavaScript 代碼在parc.js文件中,那么您需要將該文件添加到</body>
標記上方,如下面的代碼所示。
您的HTML代碼
<!DOCTYPE html>
<html>
<head>
<title>Experiments</title>
</head>
<body>
<h1>Hey there!</h1>
<script src = "prac.js"></script>
</body>
</html>
您的JavaScript代碼
var hi = document.querySelector("h1");
hi.style.color = "red";
可能您的腳本在DOM
渲染之前運行。 正如 Palash 建議的那樣,將您的腳本標簽放在正文標簽的末尾。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.