I'm trying to build a web site that cleanly separates the HTML presen开发者_运维问答tation from the JavaScript behavior.
To gain experience in this, I have created a simple "Hello, world!" site with one page and one behavior. The page contains a "Hello, world!" message, and the JavaScript displays a similar message to the user through an alert box.
To implement this, I have created two files on my local machine called index.html and sayhello.js.
The HTML file index.html contains this:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8"/>
<title>Hello, world!</title>
</head>
<body>
<h1>Helo, world!</h1>
<p>That's all for now.</p>
<script type="text/javascript" src="sayhello.js"/>
</body>
</html>
The JavaScript file sayhello.js contains this:
alert('Hello, world!');
My operating system is Windows 7.
I open index.html in Opera 11 and see a "Hello, world!" dialog pop up as soon as the page opens.
In Firefox 4, Chrome 11, and IE 9, I don't see the pop up. It's as if the JavaScript is being ignored.
Why doesn't the alert box show up in all browsers? What can I do to make it show in all?
The <script>
tag is not self-closing. You need to write
<script type="text/javascript" src="sayhello.js"></script>
Almost all browsers don't like self closing tags for the script
tag.
So simply replace it with:
<script type="text/javascript" src="sayhello.js"></script>
After seeing the other succinct answers, I did a bit of reading and found that the fundamental problem is that I'm confusing HTML and XML constructs.
According to this post from the WebKit team, self-closing tags in HTML might work because of how leniantly HTML parsers handle errors, and not because they understand the self-closing syntax:
When XML and XHTML were first standardized, no browser supported them natively. To enable at least partial use of XHTML, the W3C came up with something called “HTML-compatible XHTML”. This is a set of guidelines for making valid XHTML documents that can still more or less be processed as HTML. The basic idea is to use self-closing syntax for tags where HTML doesn’t want a close tag, like img, br or link, with an extra space before the slash. So our ever-popular image example would look like this:
<img src="funfun.jpg" />
. The details are described in the Appendix C of the XHTML 1.0 standard.It’s important to note that this is kind of a hack, and depends on the de facto error handling behavior of HTML parsers. They don’t really understand the XML self-closing syntax, but writing things this way makes them treat / as an attribute, and then discard it because it’s not a legal attribute name. And if you tried to do something like , they wouldn’t understand that the div is supposed to be empty.
Seems like the safest thing for me to do is just to close all my tags the long way.
精彩评论