开发者

Why don't these Javascript line break techniques work in my browser?

I am new to Javascript, and just trying to learn the basics. Neither of these examples display in my browser. What am I doing wrong here?

<HTML> 
<HEAD> 
<TITLE>My First JavaScript</TITLE>
</HEAD>
<BODY>
<SCRIPT LANGUAGE="JAVASCRIPT" TYPE="TEXT/JAVASCRIPT">
<!-- 
document.write("I love JavaScript") <br/> 
document.write("Craig Knaak") <br/>
document.write("It's a good day to die") <br/&开发者_Go百科gt; 
document.write('He said "Welcome to my world"')

document.write("I love JavaScript\n")
document.write("Craig Knaak\n")
document.write("It's a good day to die\n")
document.write('He said "Welcome to my world"')

//-->
</SCRIPT>
</BODY>
</HTML>


Those line breaks have to be on the inside of the quoted string.

document.write("I love JavaScript <br/>")

the <br/> isn't javascript code, its an HTML tag, and document.write will write HTML to the page, so you have to include it inside of the write string.


You need to add the br into the expression:

document.write("I love JavaScript <br/>" )


Remove the <br/> tags and you should be good.

Also \n just adds a break to the source code. To add a break on the page change the \n to <br/>


Basically, the HTML you want to output should be inside the javascript strings. Also, dont forget your ; at the end of your javascript statements. ;)

document.write("I love JavaScript<br />");
document.write("Craig Knaak<br />");
document.write("It's a good day to die<br />");
document.write('He said "Welcome to my world"');


Besides the already given answers are perfect, to insert <br/> in the strings, I would recommend you to use semicolons to end your statements. Since in this example will work mostly without them, you will experience problems someday because there are situations where automatic correction is not possible.

document.write("I love JavaScript<br/>"); // moves following text to the next line inside the browser
document.write("I love JavaScript\n"); // will not work inside the browser window 

The second line will not insert a new line in browsers since the newline character is interpreted as whitespace only, though it moves following text to a new line in text editors only (e.g. in source view of certain browsers) for better readability. Still it is good to know since it is being used in most other applications where you need to output text.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜