2013-12-19 84 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(分析)要求您執行的操作。 –

相關問題