JavaScript Uncaught TypeError: Cannot read property 'value' of null


用 JavaScript 操作 DOM 時出現如下錯誤:

   Uncaught TypeError: Cannot set property 'value' of null
   Uncaught TypeError: Cannot read property 'id' of undefined

例如:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script>
	var div = document.getElementById("測試1");
	alert(div.id);
	alert(div.className);
	alert(div.title);
</script>
<title>測試</title>
</head>
<body>
	<div id="測試1" class="測試2" title="測試3">
		<span>0</span>
		<span>1</span>
		<span>2</span>
		<span>3</span>
	</div>
</body>
</html>

運行時出現如下錯誤:

問題出在 JS 運行的時候你的頁面還沒有加載完成,所以你的 JS 代碼找不到你的頁面元素,就會拋出這個問題。解決辦法就是把 JavaScript 代碼放在 body 的最后,例如:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>測試</title>
</head>
<body>
	<div id="測試1" class="測試2" title="測試3">
		<span>0</span>
		<span>1</span>
		<span>2</span>
		<span>3</span>
	</div>
<script>
	var div = document.getElementById("測試1");
	alert(div.id);
	alert(div.className);
	alert(div.title);
</script>
</body>
</html>


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM