开发者

Javascript newbie: why is the value not printed out?

I am just starting learning JavaScript, and have a question that I am not able to understand.

I have an HTML file like this:

<html>
<head>
    <script language="javascript" src="test.js" />
    <!-- <script></script> -->
</head>
<body>
</body>
</html>

and my test.js is like this:

document.writeln("test");

Strangely enough, I do not see the string "test" printed out on the web page. It doesn't pr开发者_运维知识库int until I remove the commented out line of code in the HTML file.

Also, when I try to replace <script></script> with <script/>, there is no output either.

The question here is why the code <script></script> is related to the output?

Test was done on Chrome 10, and IE 9.


This may be a shot in the dark, but try replacing:

<script language="javascript" src="test.js" />

with:

<script language="javascript" src="test.js"></script>

I've had browsers in the past get fussy about that and not properly import the JavaScript in the former case. Technically the tag is self-closing, but it's actually expected to have a closing tag.

Edit: Following @David Dorward's comment, I did a bit of searching through specifications. I don't know which version of HTML you're using for your page, but it's probably being served as text/html and interpreted by most browsers as HTML 4.01. (Correct me if I'm wrong on this one, I'm not terribly well versed in HTML versions.)

There's a lot about the script tag here, and the interesting part is that all of the examples, be they with embedded script or a referenced script file, all supply a closing tag. A little more digging turned up this note in the XHTML 1 specification. It basically states that if a tag is meant to have content and just happens to be empty, it still needs to be closed with the full closing tag. This script element is technically empty. It's referencing an external script, but it doesn't contain that external script.

Now, these are different specifications of course. But their DTD's here and here are very similar with regards to the script element. Compare them both to, say, the br or hr elements which specify that they are empty whereas the script elements do not.


First of all, you didn't properly escape the <script> tag. Precisely, you did it, but you commented it out in this line:

<!-- <script></script> -->

That line should be:

</script>

Next, if you want to test out if your scripts work, use alert("your text") and you'll see a popup window.

The best way to see your results is to use console.log("your log text") and you'll see your debug info in Chrome's console. This will also work with Firefox if you have Firebug installed and possibly with Safari, although I haven't used it personally.


<script> needs to have a separate closing tag

<script language="javascript" src="test.js"></script>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜