【问题标题】:error: Uncaught TypeError: Cannot set property 'innerHTML' of null [duplicate]错误:未捕获的类型错误:无法设置属性“innerHTML”为空 [重复]
【发布时间】:2013-12-19 23:30:08
【问题描述】:

当我尝试在 chrome 中运行此程序时,我不断收到错误“Uncaught TypeError: Cannot set property 'innerHTML' of 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>

【问题讨论】:

  • 您的脚本在&lt;body&gt; 加载之前执行。因此,您尝试访问的元素都不存在,getElementById 返回null

标签: javascript html dom getelementbyid


【解决方案1】:

等待窗口加载:

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

或者将你的JS移到&lt;/body&gt;标签之后。

【讨论】:

  • 非常感谢!我将 JS 移动到我的 div 之后,它起作用了!
  • 如果您的代码 sn-p 在加载 html 后专门工作,您可以轻松地将 js 代码放在
猜你喜欢
  • 1970-01-01
  • 2022-10-06
  • 1970-01-01
  • 2014-06-01
  • 2014-03-06
  • 1970-01-01
相关资源
最近更新 更多