我正在通过W3C HTML Validator(http://validator.w3.org/)运行我的网站,虽然我收到了一个非常奇怪的错误。
这是逐字复制的错误:
Line 31, Column 29: character "&" is the first character of a delimiter but occurred as data
if( pageName != "blog.html" && pageName != "blog" ) {
✉
This message may appear in several cases:
You tried to include the "<" character in your page: you should escape it as "<"
You used an unescaped ampersand "&": this may be valid in some contexts, but it is recommended to use "&", which is always safe.
Another possibility is that you forgot to close quotes in a previous tag.
这只是我网站<head>
内的一小部分Javascript。这是代码:
<script type="text/javascript">
var pathName = window.location.pathname;
var pageName = pathName.substr( pathName.lastIndexOf("/") + 1 );
if( pageName != "blog.html" && pageName != "blog" ) {
document.write("<style type='text/css'>#article_intro_ag { display:none; } </style>");
}
</script>
有没有人建议为什么在HTML验证器中将其显示为错误?
编辑:对于&
个符号,此错误发生两次。
答案 0 :(得分:3)
这是通过验证 XHTML - XHTML(XML)而导致的,不会/不能对[script]元素进行特殊的CDATA修正。
它是有效的HTML (4或5) - 事实上,按照建议对字符进行编码会破坏HTML上下文中的JavaScript!
此问题可通过以下方式解决:
<!DOCTYPE HTML>
)或; 总结:XHTML 不是 HTML。
答案 1 :(得分:1)
尝试将您的javascript放在CDATA块中,如下所示:
<script type="text/javascript">
<![CDATA[
// content of your Javascript goes here
]]>
</script>
应该通过验证。为了更加安全,您可以在CDATA标记周围添加Javascript注释,以便将其隐藏在不了解CDATA标记的旧浏览器中:
<script type="text/javascript">
/* <![CDATA[ */
// content of your Javascript goes here
/* ]]> */
</script>
我承认,这个答案是“借来的”:How do I escape an ampersand in a javascript string so that the page will validate strict?