2014-02-13 95 views
0

這行代碼:爲什麼我會收到此錯誤消息?

document.getElementById("you").innerHTML="hello world"; 

讓我在JavaScript控制檯此錯誤消息:

Uncaught TypeError: Cannot set property of 'innerHTML' of null. 

有人能解釋爲什麼嗎?因爲它顯然不是空..

編輯這裏是我的代碼的其餘部分:

<!DOCTYPE html> 
<html> 
<head> 
<title></title> 

<!--<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" 
</script>--> 
<!--<script src="myjavascript2.js" type="text/javascript"></script>--> 

<link rel="stylesheet" type="text/css" href="mycss.css"> 

<script> 
document.getElementById("you").innerHTML="hello world"; 
</script> 
</head> 
<body> 


<select id="select"> 
<option>Rock</option> 
<option>Paper</option> 
<option>Scissors</option> 
</select> 



<p id="opponent">You chose:</p> 


<p id="you"></p> 

<span id="displayresult"></span> 

</body> 
</html> 
+2

很明顯'null'。至少在該代碼行運行時。 –

+1

請發表您的其他代碼。 – j08691

+0

任何接受答案的機會? – bjb568

回答

2

空。您的腳本在元素存在之前正在運行。要麼做的onload:

<div></div> 
<script></script> 
0

Cannot set property of 'innerHTML' of null.

據指出該元素不存在

它也可能是:

onload = function() { 
    document.getElementById("you").innerHTML="hello world"; 
} 

或元素之後甚至在加載元素之前檢查。

嘗試負載

document.onload = function() { 
document.getElementById("you").innerHTML="hello world"; 
}; 
0

檢查也許有id爲you沒有這樣的元素。請重新檢查該ID。

相關問題