2014-02-13 94 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。

相关问题