这是我的 html 文件的代码:
<html>
<head>
<script type="text/javascript" src="try1.js"></script>
</head>
<body>
<h1>A Web Page</h1>
<p id="demo">A Paragraph</p>
<button type="button" onclick="myFunction()">Try it</button>
</body>
</html>
这是我的 javascript 文件的代码:
function myFunction() {
document.getElementById("demo").innerHTML = "Paragraph changed";
}
最佳答案
因为该元素还不存在。尝试将 javascript 放在正文的末尾
<html>
<head>
<title>Example<title>
</head>
<body>
<h1>A Web Page</h1>
<p id="demo">A Paragraph</p>
<button type="button" onclick="myFunction()">Try it</button>
<script type="text/javascript" src="try1.js"></script>
</body>
</html>
在内联时似乎工作得很好。
<h1>A Web Page</h1>
<p id="demo">A Paragraph</p>
<button type="button" onclick="myFunction()">Try it</button>
<script type="text/javascript">
function myFunction() {
document.getElementById("demo").innerHTML = "Paragraph changed";
}
</script>
关于javascript - 为什么我的 javascript 文件无法加载?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44553525/