开发者

XHTML Strict is not valid because of html tags inside Javascript

I'm creating a site using XHTML Strict markup. Inside the html开发者_JAVA百科 I need to put a js script:

<script type="text/javascript">

$(document).ready(function () { $('#nav li#nav-strona-glowna').append('<a href="/platinium/" class="hover active"><span>Strona glowna</span></a>');

</script>   

Unfortunately the xhtml is no longer valid, because of an "" tag inside this script. How can I validate xhtml without removing it?


You want a CDATA tag. The example stolen from that MDC page:

<script type="text/javascript">
 //<![CDATA[
  var i = 0;

  while  (++i < 10)
  {
    // ...
  }
 //]]>
</script>

In general it's better to avoid the issue by having your JS (and CSS) in external files.


Try:

<script type="text/javascript">
  <![CDATA[
      $(document).ready(function () { $('#nav li#nav-strona-glowna').append('<a href="/platinium/" class="hover active"><span>Strona glowna</span></a>');
  ]]>
</script>


<script type="text/javascript"><![CDATA[
// your code
]]></script>

Should fix your problem


What error does validator gives you exactly? The code you posted looks pretty valid.

Btw. If you don't need XHTML for some very specific reason,

(http://xhtml.com/en/xhtml/serving-xhtml-as-xml/)

you're probably better off with just HTML4 or HTML5, which you can also make valid code with.


CDATA Wrapper

 <script>
 //<![CDATA[

 // js goes here - bypasses browser HTML parser

 //]]>
 </script>

I suggest that you find ways to inject HTML in your page that doesn't directly involve writing HTML markup in your JavaScript. Your relationship with your web designer will be much stronger, more cooperative, and fruitful if you keep your content, presentation, and behavior separated.

But for those cases where that is not possible, a CDATA wrapper will prevent the browser from parsing your JavaScript as HTML.

Keep in mind that there is a reason they call it HTML Strict.


Update

There's a problem in your code, which is that it's missing a close brace and parenthesis. Possibly a typo?

Regarding the XHTML validation, the best option is to put you JavaScript in a separate file. Failing that, add a CDATA section around your script:

<script type="text/javascript">
//<![CDATA[
    $(document).ready(function () { $('#nav li#nav-strona-glowna').append('<a href="/platinium/" class="hover active"><span>Strona glowna</span></a>'); });
//]]>
</script>

Note that the JavaScript comments are there for browsers such as IE which do not parse XHTML as XML. See https://developer.mozilla.org/en/properly_using_css_and_javascript_in_xhtml_documents

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜