我是 HTML 和 Javascript 新手。我正在测试的是点击一个按钮,然后引用一个 JS 脚本。但是当我打开我的网站时,它不断抛出“ReferenceError:找不到变量:hello”,hello
是我在脚本中定义的函数。网页是用docker部署的。
我多次尝试更改 src 路径,但仍然出错
这是主页。
<html>
<head>
<title>My Page</title>
</head>
<body>
<p>Click the button to sort the list alphabetically:</p>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script>
if(typeof jQuery!=='undefined'){
console.log('jQuery Loaded');
}
else{
console.log('not loaded yet');
}
</script>
<button onclick="hello('JLKLJSDLFJKSDLKFKJLSDJKLFJLKS')">HAHA7</button>
<script type="text/javascript" language="javascript" src="js/test.js"></script>
<p>The date today is {{.Date}}</p>
<p>And the time is {{.Time}}</p>
</body>
</html>
这是脚本:
hello = function (arg) {
document.write(arg);
}
这是我的文件结构:
.
├── dockerfile
├── go.mod
├── go.sum
├── k8s
│ ├── alb-ingress-controller.yaml
│ ├── aws-auth-cm.yaml
│ ├── eks-admin-cluster-role-binding.yaml
│ ├── eks-admin-service-account.yaml
│ ├── ingress.yaml
│ ├── inventory-deployment.yaml
│ ├── inventory-namespace.yaml
│ ├── inventory-service.yaml
│ └── rbac-role.yaml
├── README.md
├── server.go
└── template
├── ec2.html
├── homepage.html
├── js
│ ├── sort.js
│ └── test.js
├── login.html
├── rds.html
└── redis.html
现在错误是当我点击“HAHA7”按钮时,它显示“ReferenceError:找不到变量:你好”,谢谢大家!
最佳答案
您可以尝试使用绝对链接,将脚本标记移动到页面底部并使用 JavaScript 事件而不是内联事件,如下所示:
<!DOCTYPE html>
<html>
<head>
<title>My Page</title>
</head>
<body>
<p>Click the button to sort the list alphabetically:</p>
<button id="my-button">HAHA7</button>
<p>The date today is {{.Date}}</p>
<p>And the time is {{.Time}}</p>
<script type="text/javascript">
if(typeof jQuery !== 'undefined') {
console.log('jQuery Loaded');
} else{
console.log('not loaded yet');
}
</script>
<script type="text/javascript" src="/js/test.js"></script>
<script type="text/javascript">
document.querySelector("#my-button").addEventListener("click", () => {
someBadWord('JLKLJSDLFJKSDLKFKJLSDJKLFJLKS');
});
</script>
</body>
</html>
祝你好运。
关于javascript - 我无法在 html 中使用 src =""引用 javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56627507/