[英]Why can't I attach javascript to my html?
No matter how I choose to add a javascript file to a html file, it doesn't seem to work. 不管我如何选择将javascript文件添加到html文件,它都似乎不起作用。 My original code is longer and has more stuff in it but I thought I would isolate the problem and see if with a very basic bit of code I would get the same problem (which I do).
我的原始代码较长,并且包含更多内容,但是我想我可以隔离问题,然后看看是否使用非常基本的代码我也会遇到相同的问题(我可以这样做)。
I've tried adding the script tag to the head and to the body (at the start and at the end). 我尝试将script标签添加到头部和身体(在开头和结尾)。
Brackets states that the function is never called and also seems to think that alert doesn't exist. 方括号指出该函数从未调用过,并且似乎还认为警报不存在。 If I add internal javascript it works.
如果我添加内部javascript,则可以使用。
in Chrome's console it reads: 在Chrome的控制台中,它显示为:
test.html:1 Uncaught ReferenceError: helloWorld is not defined
at HTMLButtonElement.onclick (test.html:1) onclick @ test.html:1
when I click the button. 当我单击按钮时。
HTML is: HTML是:
<!doctype>
<head>
<title>testcode</title>
<script src="test.js"></script>
</head>
<body>
<button onclick="helloWorld()">Press to say hello world</button>
</body>
test.js is in the same folder and is: test.js在同一文件夹中,并且是:
function helloWorld() {
alert("Hello World!");
}
UPDATE: I changed nothing and just reopened the browser, now it works (currently missing python a lot). 更新:我什么都没改变,只是重新打开了浏览器,现在它可以工作了(目前缺少很多python)。
The code is working for me. 该代码为我工作。 Maybe it's the path of the files.
也许这是文件的路径。 If the files are in the same level, it should works..
如果文件处于同一级别,则应该可以使用。
- index.html
- test.js
But if the script is in a folder, you should change the script tag. 但是,如果脚本位于文件夹中,则应更改脚本标签。 Exemple :
范例:
- index.html
- /js
- test.js
<script src="js/test.js"></script>
There is another case, if your html page is /article/hello
and your js /test.js
you should change the script tag with <script src="../test.js"></script>
还有一种情况,如果您的html页面是
/article/hello
而您的js是/test.js
,则应使用<script src="../test.js"></script>
更改脚本标签。
It's working for me. 它为我工作。 I just copied and pasted your exact code and it was working for me.
我只是复制并粘贴了您的确切代码,它对我有用。 Make sure you have saved both html and js files in same directory.
确保已将html和js文件保存在同一目录中。
In order to check if JS file is included just open Developers Options (Ctrl+Shift+I) in chrome and then see if you get any error like this(in case js file was not included) 为了检查是否包含JS文件,只需在Chrome中打开开发人员选项(Ctrl + Shift + I),然后查看是否会出现这样的错误(如果不包含js文件)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.