使用 document.getElementById 时,它无法正常工作

When using document.getElementById, it's not working properly

问题
我正在尝试将函数的输出显示到 div,但我不明白为什么它不显示。我怎样才能解决这个问题,以便它正确显示?

到目前为止我尝试了什么
我从我编写的另一个正在运行的代码块中复制了一个 document.getElementById 语句,并检查了它是否有任何拼写错误等。一切看起来都很好。 我用谷歌搜索了 innerHTML 以确保我正确使用了它。
还将 document.etc 行更改为 document.write 以确保函数正常工作,输出正常。


我的代码

<html>
<head>    
<script type="text/javascript">
    function parameters(one, two) {
        document.getElementById('output').innerHTML=(one + two);
    }

    parameters("coding" , "coffee");
</script>
</head>    
<body>
    <div id="output"></div>
</body>
</html>

问题是您试图在浏览器加载 div#output 之前使用它。

有两个简单的解决方案:

第一个

<script> 标签放在 div#output 之后,这样它就会被加载。

<html>
<head>
</head>
<body>
  <div id="output"></div>
  <script type="text/javascript">
    function parameters(one, two) {
      document.getElementById('output').innerHTML=(one + two);
    }

    parameters("coding" , "coffee");
  </script>
</body>
</html>

第二个

将您的 Javascript 代码放在 DOMContentLoaded 事件中,这样它只会在您的页面中加载所有 DOMElement 后调用。

<html>
<head>
  <script type="text/javascript">
    function parameters(one, two) {
      document.getElementById('output').innerHTML=(one + two);
    }

    document.addEventListener('DOMContentLoaded', function() {
      parameters("coding" , "coffee");
    });
  </script>
</head>
<body>
  <div id="output"></div>
</body>
</html>