[英]I can't figure out why my JavaScript file won't display when linked
I can't figure out what's wrong here and I'm not getting any output from the Javascript file. 我无法弄清楚这里出了什么问题,也没有从Javascript文件中获得任何输出。 I am trying to use src to be able to type my javascript file outside of the index file.
我正在尝试使用src来在索引文件之外键入我的javascript文件。 This just prints the header from the html file "A test heading" without printing the text variable.
这只是从html文件“测试标题”中打印标题,而不打印text变量。 If I type the code within the html file it works fine.
如果我在html文件中键入代码,则可以正常工作。 Both scripts are in the same folder.
这两个脚本位于同一文件夹中。
<!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 - 这是标记为slide.js的文件-
function slider(){
var text = "Welcome to Slider Simulator 2013!";
document.write(text);
}
slider();
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. 内容必须放在
<body>
,而不是其他任何地方。 <head>
is usually for scripts, styles, page metadata, but not the content. <head>
通常用于脚本,样式,页面元数据,但不适用于内容。
Also, language
can be omitted since <script>
run JavaScript by default anyway. 另外,由于
<script>
默认运行JavaScript,因此可以省略language
。
You're using HTML5 doctype, just use this and remove script language : 您正在使用HTML5文档类型,只需使用它并删除脚本语言即可:
<script src="/slider.js"></script>
You should avoid document.write
as it's not a reliable way to output data to your page. 您应该避免使用
document.write
因为这不是将数据输出到页面的可靠方法。 If you ever use it after the window has finished loading, it'll replace all the html contents with the new content. 如果您在窗口加载完成后使用它,它将用新内容替换所有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>
<!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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.