javascript - 将JS拆分成多个源文件
问题描述
提前道歉,我有一个关于 JS 的非常愚蠢/基本的问题。
我正在尝试将脚本(在单独的 JS 文件中定义)链接到按钮:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script type="text/javascript" src="myscripts.js"></script>
</head>
<body>
<input type="button" id="button" value="Button">
<script>
button.onclick = function() {
alert('Clicked!');
};
</script>
</body>
</html
myscripts.js
有这个:
function x (){
alert("external fn clicked");
console.log("running x");
}
当我尝试将函数调用替换为index.html
停止button.onclick = x();
工作时。
我究竟做错了什么?
解决方案
您需要将 onclick 设置为一个函数,但似乎您正在做的是将其设置为 x 函数的返回值,即undefined
.
只需更改button.onclick = x()
为button.onclick = x
.
同样在现代,通常最好使用button.addEventListener(x)
.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script>
function x() {
alert("external fn clicked");
console.log("running x");
}
</script>
</head>
<body>
<input type="button" id="button" value="Button">
<script>
button.onclick = x;
</script>
</body>
</html
推荐阅读
- php - 试图从一个数据库中获取用户名并将其与消息一起粘贴到另一个数据库
- kubernetes - 如何将字典包含到 k8s_raw 数据字段中
- jira - 将 AWS 设备场与 Jira 集成?
- ios - 同一个视图控制器出现两次
- android - 如何将加载栏添加到视图位于另一个活动中的适配器类
- bash - 通过匹配 iptables 和 netstat 的脚本检查打开的 WAN 端口?
- angular - 如何将字符串参数转换为变量 TypeScript Angular 的属性
- python - 无法在python中获取反转的字符串
- django - 调用 CreateMultipartUpload 操作时发生错误 (SignatureDoesNotMatch):
- c# - 如何从窗口服务内部在浏览器中加载网页