2013-12-19 82 views
7

当我尝试在chrome中运行此程序时,我一直在收到错误“Uncaught TypeError:无法设置属性'innerHTML'为null”。我现在不做什么我做错了,任何帮助,将不胜感激。错误:未捕获TypeError:无法设置为null的属性'innerHTML'

<!DOCTYPE html> 
<html> 
<head> 
</head> 
<script> 
    var x = "hey"; 
    var counter = 1; 
    var button = document.getElementById("button"); 
    var div = document.getElementById("box"); 
    var text = document.getElementById("text"); 
    var sound = document.getElementById("sound"); 
    var array=[ "thanks for clicking", "keep on clicking", "click one more time", "why do you keep on clicking me?", "stop clicking me!"]; 
function thing(file){ 
    var y = array[Math.floor(Math.random() * array.length)]; 
     if (x == y){ 
      while (y == x){ 
       var y = array[Math.floor(Math.random() * array.length)]; 
     } 
     } 
    form1.text.value=y; 

    x = y; 
sound.innerHTML = "<embed src=\""+file+"\"hidden=\"true\"autostart=\"true\" loop=\"false\"/>"; 

} 
</script> 
</head> 
<body> 
<form name="form1"> 
<input type="button" id="button" value="click" onClick="thing('sound.mp3')" /> 
    <input type="text" id="text" value="hey" /> 
</form> 
<div id="sound"> 
<p> 
</p> 
</div> 
</body> 
</html> 
+4

您的脚本在加载''之前执行。因此,您尝试访问的元素都不存在,并且'getElementById'返回'null'。 – 0x499602D2

回答

38

等待窗口加载:

window.onload = function() 
{ 
    //yourJSCodeHERE 
} 

</body>标签后,移动你的JS。

+0

非常感谢!我把JS移到我的div之后,它就起作用了! –

+1

如果您的代码片段在加载html后专门工作,您可以轻松地将js代码置于标记的末尾之前......类似于Google Analytics(分析)要求您执行的操作。 –

相关问题