这是我的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;
当我在浏览器中加载index.html时,我看不到显示的123。为什么这样?
<!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>
答案 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?