我不明白为什么我的 JavaScript 文件在链接时不会显示
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16599289/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
I can't figure out why my JavaScript file won't display when linked
提问by Bennet Leff
I can't figure out what's wrong here and I'm not getting any output from the Javascript file. I am trying to use src to be able to type my javascript file outside of the index file. This just prints the header from the html file "A test heading" without printing the text variable. If I type the code within the html file it works fine. Both scripts are in the same folder.
我无法弄清楚这里出了什么问题,而且我没有从 Javascript 文件中获得任何输出。我正在尝试使用 src 以便能够在索引文件之外键入我的 javascript 文件。这只是打印来自 html 文件“A 测试标题”的标题,而不打印文本变量。如果我在 html 文件中输入代码,它工作正常。两个脚本都在同一个文件夹中。
<!DOCTYPE HTML>
<html>
<head>
<h2>
A Test Heading
</h2>
<script language = "JavaScript" src="/slider.js"></script>
</head>
</html>
Here's the file labeled slider.js -
这是标记为 slider.js 的文件 -
function slider(){
var text = "Welcome to Slider Simulator 2013!";
document.write(text);
}
slider();
采纳答案by Joseph
If the script is in the same folder as the HTML file, then you can just do:
如果脚本与 HTML 文件位于同一文件夹中,则您可以执行以下操作:
<script src="slider.js"></script>
The starting /
means "from the root", and the root might not be what you'd expect. Root does not mean the location of the HTML that loaded it, but the root of the file system or the domain.
开始的/
意思是“从根”,而根可能不是您所期望的。根并不意味着加载它的 HTML 的位置,而是文件系统或域的根。
Content must be placed inside the <body>
, and not anywhere else. <head>
is usually for scripts, styles, page metadata, but not the content.
内容必须放在 内<body>
,而不是其他任何地方。<head>
通常用于脚本、样式、页面元数据,而不是内容。
Also, language
can be omitted since <script>
run JavaScript by default anyway.
此外,language
可以省略,因为<script>
无论如何都默认运行 JavaScript。
回答by AlienWebguy
You're using HTML5 doctype, just use this and remove script language :
您正在使用 HTML5 doctype,只需使用它并删除脚本语言:
<script src="/slider.js"></script>
You should avoid document.write
as it's not a reliable way to output data to your page. If you ever use it after the window has finished loading, it'll replace all the html contents with the new content.
您应该避免,document.write
因为它不是将数据输出到页面的可靠方式。如果您在窗口完成加载后使用它,它将用新内容替换所有 html 内容。
<html>
<head>
<title> The title goes here </title>
<script src="/slider.js"></script>
</head>
<body>
<h2> A Test Heading (this goes in the body) </h2>
</body>
</html>
回答by Aadi Nayar
<!DOCTYPE html>
<html>
<head>
<title>LOL UR CAT SUX</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=0">
</head>
<body>
<h1>
LOL UR CAT STILL SUX
</h1>
<p>
LOL UR CAT STILL <i>REALLY</i> SUX
</p>
</body>
</html>