Extensible HyperText Markup Language( XHTML) is a reformulation of HTML as an application of XML. The rules for writing code in XHTML are stricter than those for HTML, which affects the <script>element when using embedded JavaScript code. Although valid in HTML, the following code block is invalid in XHTML:
<script type=”text/javascript”>
function compare(a, b) {
if (a < b) {
alert(“A is less than B”);
} else if (a > b) {
alert(“A is greater than B”);
} else {
alert(“A is equal to B”);
}
}
</script>
In HTML, the <script>element has special rules governing how its contents should be parsed; in XHTML, these special rules don’t apply. This means that the less-than symbol (<) in the statement a < b is interpreted as the beginning of a tag, which causes a syntax error because a less-than symbol must not be followed by a space.
There are two options for fixing the XHTML syntax error. The first is to replace all occurrences of he less-than symbol (<) with its HTML entity (<). The resulting code looks like this:
<script type=”text/javascript”>
function compare(a, b) {
if (a < b) {
alert(“A is less than B”);
} else if (a > b) {
alert(“A is greater than B”);
} else {
alert(“A is equal to B”);
}
}
</script>
This code will now run in an XHTML page; however, the code is slightly less readable. Fortunately, there is another approach.
The second option for turning this code into a valid XHTML version is to wrap the JavaScript code in a CDATA section. In XHTML (and XML), CDATA sections are used to indicate areas of the document that contain free-form text not intended to be parsed. This enables you to use any character, including the less-than symbol, without incurring a syntax error. The format is as follows:
<script type=”text/javascript”><![CDATA[
function compare(a, b) {
if (a < b) {
alert(“A is less than B”);
} else if (a > b) {
alert(“A is greater than B”);
} else {
alert(“A is equal to B”);
}
}
]]></script>
In XHTML-compliant web browsers, this solves the problem. However, many browsers are still not XHTML-compliant and don’t support the CDATA section. To work around this, the CDATA markup must be offset by JavaScript comments:
<script type=”text/javascript”>
//<![CDATA[
function compare(a, b) {
if (a < b) {
alert(“A is less than B”);
} else if (a > b) {
alert(“A is greater than B”);
} else {
alert(“A is equal to B”);
}
}
//]]>
</script>
This format works in all modern browsers. Though a little bit of a hack, it validates as XHTML and degrades gracefully for pre-XHTML browsers.
Không có nhận xét nào:
Đăng nhận xét