为什么这段代码不能正常使用getElementById?

问题描述 投票:0回答:2

任何人都可以告诉我为什么显示document.getElementById("ibody").innerHTML=...的代码不起作用?

<script type="text/javascript">
    var v=new Date();
    document.write("Avec document.write() = "+v);
    window.alert("Avec window.alert() = "+v);
    alert("Avec alert() = "+v);
    console.log("Avec console.log = "+v);
    document.getElementById("ibody").innerHTML=
        "Avec getElementById() ds DIV = "+v
</script>

<body id="ibody"></body>
alert document getelementbyid console.log
2个回答
0
投票

将javascript代码保存在声明的正文下


0
投票

因为在运行代码时,<body>元素不存在。

尝试将代码块包装在DOM完成加载后运行的事件处理程序中:

<script type="text/javascript">
    document.addEventListener(
        'DOMContentLoaded',
        function () {
            var v=new Date();
            document.write("Avec document.write() = "+v);
            window.alert("Avec window.alert() = "+v);
            alert("Avec alert() = "+v);
            console.log("Avec console.log = "+v);
            document.getElementById("ibody").innerHTML=
                "Avec getElementById() ds DIV = "+v
        }
    );
</script>
© www.soinside.com 2019 - 2024. All rights reserved.