I can't figure out why my JavaScript file won't display when linked

我们两清 提交于 2019-12-24 03:03:17

问题


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.

<!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 -

function slider(){  
var text = "Welcome to Slider Simulator 2013!";

document.write(text);
}
slider();

回答1:


If the script is in the same folder as the HTML file, then you can just do:

<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.

Content must be placed inside the <body>, and not anywhere else. <head> is usually for scripts, styles, page metadata, but not the content.

Also, language can be omitted since <script> run JavaScript by default anyway.




回答2:


You're using HTML5 doctype, just use this and remove script language :

<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.

<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>



回答3:


<!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>


来源:https://stackoverflow.com/questions/16599289/i-cant-figure-out-why-my-javascript-file-wont-display-when-linked

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!