为什么我收到此错误消息?

时间:2014-02-13 17:37:52

标签: javascript

这行代码:

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>

3 个答案:

答案 0 :(得分:2)

null。您的脚本在元素存在之前运行。要么是onload:

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

或在元素之后:

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

答案 1 :(得分:0)

<强> Cannot set property of 'innerHTML' of null.

表示该元素不存在

甚至可能在加载元素之前检查它。

尝试检查加载

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

答案 2 :(得分:0)

也许没有ID为you的元素。请重新检查身份证。

相关问题