错误:未捕获TypeError:无法设置null的属性'innerHTML'

时间:2013-12-19 23:30:09

标签: javascript html html5 dom getelementbyid

当我尝试在chrome中运行此程序时,我继续收到错误“Uncaught TypeError:无法设置属性'innerHTML'为null”。我现在不知道我做错了什么,而且任何帮助都会受到赞赏。

<!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>

1 个答案:

答案 0 :(得分:37)

等待窗口加载:

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

或在</body>代码后移动您的JS。