简体   繁体   English

javascript-为什么innerHTML替换无法运行?

[英]javascript - Why doesn't innerHTML replacing run?

<!DOCTYPE HTML>
<html>
<head>
<script>
document.write("TEST1")
document.getElementById("demo").innerHTML="TEST2"
document.write("TEST3")
</script>
</head>

<body>
<p id="demo">TO_BE_REPLACED</p>
</body>
</html>

Here is the output: TEST1 这是输出:TEST1

TO_BE_REPLACED

It seems the javascript executing stopped at document.getElementById("demo").innerHTML="TEST2" . 看来javascript执行已在document.getElementById("demo").innerHTML="TEST2"处停止。 Why doesn't it execute? 为什么不执行?

When the script is being run, <p id="demo"> does not exist yet . 运行脚本时, <p id="demo"> 尚不存在 Therefore, document.getElementById('demo') is returning null , which then triggers an error when you try to assign null.innerHTML = "TEST2" 因此, document.getElementById('demo')返回null ,然后在您尝试分配null时触发错误null.innerHTML = "TEST2"

This error stops all execution, so you never get to see the final TEST3 . 此错误将停止所有执行,因此您永远看不到最终的TEST3

You need to enclose your script in a function that will be called when the window loads (using "window.onload" event). 您需要将脚本封装在加载窗口时将调用的函数中(使用“ window.onload”事件)。

<!DOCTYPE HTML>
<html>
<head>
<script>
    function replaceDemoText()
    {
        document.getElementById("demo").innerHTML="TEST2";
    }
    window.onload = replaceDemoText;
</script>
</head>

<body>
<p id="demo">TO_BE_REPLACED</p>
</body>
</html>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM