04.11.2015 Views

javascript

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 2: JavaScript in HTML<br />

For information on more ways to achieve functionality similar to that of the defer attribute, see<br />

Chapter 12 .<br />

Changes in XHTML<br />

Extensible HyperText Markup Language, or XHTML, is a reformulation of HTML as an application<br />

of XML. The rules for writing code in XHTML are stricter than those for HTML, which affects the<br />

< script/ > element when using embedded JavaScript code. Although valid in HTML, the following<br />

code block is invalid in XHTML:<br />

< script type=”text/<strong>javascript</strong>” ><br />

function compare(a, b) {<br />

if (a < b) {<br />

alert(“A is less than B”);<br />

} else if (a > b) {<br />

alert(“A is greater than B”);<br />

} else {<br />

alert(“A is equal to B”);<br />

}<br />

}<br />

< /script ><br />

In HTML, the < script > element has special rules governing how its contents should be parsed; in<br />

XHTML, these special rules don ’ t apply. This means that the less - than symbol ( < ) in the statement a < b<br />

is interpreted as the beginning of a tag, which causes a syntax error because a less - than symbol must not<br />

be followed by a space.<br />

There are two options for fixing the XHTML syntax error. The first is to replace all occurrences of the<br />

less - than symbol ( < ) with its HTML entity ( & lt; ). The resulting code looks like this:<br />

< script type=”text/<strong>javascript</strong>” ><br />

function compare(a, b) {<br />

if (a &lt; b) {<br />

alert(“A is less than B”);<br />

} else if (a > b) {<br />

alert(}A is greater than B”);<br />

} else {<br />

alert(“A is equal to B”);<br />

}<br />

}<br />

< /script ><br />

This code will now run in an XHTML page; however, the code is slightly less readable. Fortunately, there<br />

is another approach.<br />

17

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!