简体   繁体   English

通过javascript生成html:避免htmltidy错误

[英]html generation via javascript: avoiding htmltidy error

I have a web page that generates HTML via JavaScript. 我有一个通过JavaScript生成HTML的网页。

When validating using HTML validator 0.9.5.1 in Firefox 22, I get an error: 'document type does not allow element "span" here' 在Firefox 22中使用HTML验证器0.9.5.1进行验证时,出现错误: '文档类型不允许元素“span”here'

I am using this JavaScript: 我正在使用这个JavaScript:

 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 ...<body>...
 <script type='text/javascript'>
var someHtml = '<span>Hello world!</span>';
var e;
e = window.document.createElement('div');
e.innerHTML = someHtml;
window.document.body.appendChild(e);
 </script>

Obviously the parser assumes that <span> is nested inside <script> 显然,解析器假定<span>嵌套在<script>

How should i rewrite the JavaScript to pass HTML validation? 我应该如何重写JavaScript来传递HTML验证? I would prefer a solution that does not require me to create HTML elements. 我更喜欢不需要我创建HTML元素的解决方案。

Note: The answers in Avoiding HTML-in-string / html() in a jQuery script do not help me since I know that the code works. 注意: 在jQuery脚本避免HTML-in-string / html()的答案对我没有帮助,因为我知道代码有效。 I want to reformat to avoid validation errors. 我想重新格式化以避免验证错误。

You can't put <div> inside <pre> . 你不能把<div>放在<pre>里面。 <pre> can contain phrasing content only, where <div> is not. <pre>只能包含短语内容 ,而<div>则不包含。

Also you should wrap your script with <![CDATA[ ... ]]> section since doctype is XHTML. 此外,您应该使用<![CDATA[ ... ]]>部分包装脚本,因为doctype是XHTML。

the pre element is for preformatted text, not more HTML. pre元素用于预格式化文本,而不是HTML。

HTML Tidy's objection is that you are putting something that it believes you expect the browser to render as HTML, you need to scape the entities (replacing < and > with &lt; and &gt; ) so that it is interpretted as text. HTML Tidy的反对意见是,您正在放置它认为您希望浏览器呈现为HTML的内容,您需要对实体进行检索(将<>替换为&lt;&gt; )以便将其解释为文本。

UPDATE IN RESPONSE TO COMMENT : With an XHTML doctype, the document must be wellformed XML. 响应评论的更新 :使用XHTML doctype,文档必须是格式良好的XML。 So, you need CDATA marks inside your script tag: 因此,您需要在脚本标记内添加CDATA标记:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
  <head>
    <title>Hello world</title>
  </head>
  <body>
  <script type='text/javascript'>
  //<![CDATA[
  var someHtml = "<div>Hello world!</div>";
  var e;
  e = window.document.createElement('div');
  e.innerHTML = someHtml;
  window.document.body.appendChild(e);
  //]]>
  </script>
  </body>
</html>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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