HTML 文件
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<p id="hi">HI</p>
<br>
<input type="button" onclick="onClick1()" value ="CLICK ME">
<script src="myfunc.js"></script>
</body>
</html>
脚本
<script>
function onClick1(){
document.getElementById("hi").innerHTML = "hello";
}
</script>
Google Chrome 显示 LocalException:ReferenceError: onClick1 未在 HTMLInputElement.onclick 中定义
.js 和 html 文件保存在桌面上的同一文件夹中...
最佳答案
去掉myfunc.js
文件中的script标签,写入如下。这是因为在文档“准备好”之前无法安全地操作页面。
$(document).ready(function(){
function onClick1(){
document.getElementById("hi").innerHTML = "hello";
}
});
仅当您将脚本(此处为 onClick1()
函数)包含在 HTML 文件本身内时,才需要包含 script 标记,如下所示。
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<p id="hi">HI</p>
<br>
<input type="button" onclick="onClick1()" value ="CLICK ME">
<script>
function onClick1(){
document.getElementById("hi").innerHTML = "hello";
}
</script>
</body>
</html>
关于javascript - 外部 javascript/HTML 不工作...非常基本的基本/初学者,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48091103/