为什么elem.innerHTML在这里不起作用?

时间:2017-09-03 02:00:19

标签: javascript html

这是我的script.js



document.addEventListener("DOMContentLoaded", function() {
  // this function runs when the DOM is ready, i.e. when the document has been parsed
  var elem = document.getElementById("output");
  elem.innerHTML = 123;
});

<h1>Hello!</h1>
<div id="output">11</div>
&#13;
&#13;
&#13;

当我在浏览器中加载index.html时,我看不到显示的123。为什么这样?

原始HTML

<!DOCTYPE html>
<html>
<head>
    <title>My page</title>
    <script async type="text/javascript" src="script.js"></script>
</head>
<body>
    <h1>Hello!</h1>
    <div id="output">11</div>
</body>
</html>

1 个答案:

答案 0 :(得分:2)

在您的修订后历史记录中,您之前有<script async type="text/javascript" src="script.js">

async指示浏览器可以独立运行。这意味着它也可以在 DOMContentLoaded被解雇后运行。删除async,事件将可靠地触发。

Async-loaded scripts with DOMContentLoaded or load event handlers not being called?

enter image description here