javascript <![CDATA[的web标准使用方法
2010-01-15 00:00:00 来源:WEB开发网二:工作在html模式下,不兼容XML解析器(来自http://www.w3.org/TR/html401/interact/scripts.html#h-18.3.2),代码如下:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="zh-Hans" lang="zh-Hans">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<title>test</title>
<script type="text/javascript">
<!--
if(1<2)
{
alert('a');
}
//-->
</script>
</head>
<body>
<p>html,It works.
</p>
</body>
</html>
为什么说上面这段代码不兼容XML解析器呢?
请看:http://www.w3.org/TR/2002/REC-xhtml1-20020801/#C_4
W3C 的解释是:Note that XML parsers are permitted to silently remove the contents of comments. Therefore, the historical practice of "hiding" scripts and style sheets within "comments" to make the documents backward compatible is likely to not work as expected in XML-based user agents.
即:在XML语法中,<!--作为注释,会被XML解析器忽略,所以把javascript放在其中导致不执行。
把下面这段XHTML标准模式代码保存为itworks.xhtml,就可以看出来javascript不执行。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="zh-Hans">
<head>
<meta http-equiv="Content-Type" content="application/xhtml+xml;charset=utf-8" />
<title>test</title>
<script type="text/javascript">
<!--
if(1<2)
{
alert('a');
}
//-->
</script>
</head>
<body>
<p>xhtml,It works.
</p>
</body>
</html>
参考资料:
http://www.cnblogs.com/scugzbc/archive/2008/07/13/1242063.html
Tags:javascript lt CDATA
编辑录入:爽爽 [复制链接] [打 印]更多精彩
赞助商链接