简体   繁体   中英

Why does my site not validate?

I am running my site through the W3C HTML Validator ( http://validator.w3.org/ ), although I am getting a very odd error.

This is the error copied word for word:

 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 "&lt;"
You used an unescaped ampersand "&": this may be valid in some contexts, but it is recommended to use "&amp;", which is always safe.
Another possibility is that you forgot to close quotes in a previous tag.

This is just a very small piece of Javascript within the <head> of my site. This is the code:

<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>

Does anyone have any suggestions to why this is being displayed as an error within a HTML validator?

EDIT: This error occurs twice, for both & symbols.

This caused by validating against XHTML - XHTML, being XML, doesn't/can't make special CDATA amends for [script] elements.

It is valid as HTML (4 or 5) - in fact, encoding the characters as suggested will break the JavaScript in an HTML context!

This issue can be resolved by:

  • Ensuring the server sends the HTML (not XHMTL/XML) Content-Type and/or;
  • Using an HTML doctype (eg <!DOCTYPE HTML> ) or;
  • Explicitly telling the validator to check against HTML or;
  • Writing valid XHTML, if the source is indeed XHTML

In summary: XHTML is not HTML.

Try putting your javascript inside a CDATA block like this:

<script type="text/javascript">
<![CDATA[
// content of your Javascript goes here
]]>
</script>

which should make it pass validation. To be extra safe you can add Javascript comments around the CDATA tags to hide them from older browsers who don't understand the CDATA tag:

<script type="text/javascript">
/* <![CDATA[ */
// content of your Javascript goes here
/* ]]> */
</script>

I admit, this answer is "borrowed" from: How do I escape an ampersand in a javascript string so that the page will validate strict?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM