[英]How to fix src attribute in script tag
This is my code in my html:这是我在 html 中的代码:
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<button onclick="run">Hello World</button>
</body>
<script src="index.js">
</script>
</html>
And this is my file index.js code, which is in the same folder:这是我的文件 index.js 代码,它在同一个文件夹中:
function run() {
console.log('Example');
alert()
}
My problem is, the button won't reach the function run(), it's not recognising it.我的问题是,按钮无法到达函数 run(),它无法识别它。 I also tried doing run() on the onclick="" And still didnt work.我也尝试在 onclick="" 上执行 run() 并且仍然没有工作。
You need to change the onclick function call as below.您需要更改 onclick 函数调用,如下所示。
function run() { console.log('Example'); alert('Test') }
<!DOCTYPE html> <html> <head> <title></title> </head> <body> <button onclick="run();">Hello World</button> </body> <script src="index.js"></script> </html>
The reason that the code does not run is because you forgot to include ()
after the function name.代码不运行的原因是你忘记在函数名后包含()
。
If you instead write your button like this it will work:如果您改为这样编写按钮,它将起作用:
<button onclick="run()">Hello World</button>
While I'm at it, I might also suggest at least moving the script
tag to the bottom of the body
tag, instead of having it outside.当我在做的时候,我也可能建议至少将script
标签移到body
标签的底部,而不是把它放在外面。 Alternatively, you could write <script defer src="...
and put it in the <head>
tag或者,您可以编写<script defer src="...
并将其放在<head>
标记中
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.