如何在网页上显示HTML片段,而不需要将每个<替换为&lt;>和&gt;?

换句话说,是否有一个标记表示在点击结束标记之前不呈现HTML ?


当前回答

function escapeHTML(string)
    { 
        var pre = document.createElement('pre');
        var text = document.createTextNode(string);
        pre.appendChild(text);
        return pre.innerHTML;
}//end escapeHTML

它将返回转义的Html

其他回答

很简单.... 使用此xmp代码

    <xmp id="container">

&lt;xmp &gt;

    <p>a paragraph</p>

    &lt;/xmp &gt;

</xmp>

是否有一个标签表示在点击结束标签之前不呈现HTML ?

不,没有。在HTML中,除了转义某些字符外,没有其他方法:

& as & < as &lt;

(顺便说一句,没有必要转义>,但人们经常这样做是为了对称。)

当然,您应该将结果转义的HTML代码包围在<pre><code>…</code></pre>中,以(a)保留空格和换行符,并(b)将其标记为代码元素。

所有其他解决方案,如将代码包装到<textarea>或(已弃用)<xmp>元素,都会破坏1

向浏览器声明为XML的XHTML(通过HTTP Content-Type报头!-仅仅设置DOCTYPE是不够的)也可以使用CDATA部分:

<![CDATA[Your <code> here]]>

但这只适用于XML,而不适用于HTML,而且这也不是一个万无一失的解决方案,因为代码不能包含结束分隔符]]>。因此,即使在XML中,最简单、最健壮的解决方案也是通过转义。


1 .恰当的例子:

不;教室:100%;} < textarea readonly =“readonly > <p>电脑<textarea>说</textarea> <span>no.</span> < / textarea > < xmp > 计算机<xmp>说</xmp> <span>no.</span> < / xmp >

我认为:

你想要编写100%有效的HTML5 你想把代码片段(几乎)文字放在HTML中 特别是<应该不需要转义

你所有的选项都在这棵树里:

with HTML syntax there are five kinds of elements those called "normal elements" (like <p>) can't have a literal < it would be considered the start of the next tag or comment void elements they have no content you could put your HTML in a data attribute (but this is true for all elements) that would need JavaScript to move the data elsewhere in double-quoted attributes, " and &thing; need escaping: &quot; and &amp;thing; respectively raw text elements <script> and <style> only they are never rendered visible but embedding your text in Javascript might be feasable Javascript allows for multi-line strings with backticks it could then be inserted dynamically a literal </script is not allowed anywhere in <script> escapable raw text elements <textarea> and <title> only <textarea> is a good candidate to wrap code in it is totally legal to write </html> in there not legal is the substring </textarea for obvious reasons escape this special case with &lt;/textarea or similar &thing; needs escaping: &amp;thing; foreign elements elements from MathML and SVG namespaces at least SVG allows embedding of HTML again... and CDATA is allowed there, so it seems to have potential with XML syntax covered by Konrad's answer

 

注意:>从来不需要转义。甚至在正常元素中也没有。

一种简单的方法来显示代码将包括它在一个文本区域和添加禁用属性,所以它是不可编辑的。

<textarea disabled> code </textarea>

希望这能帮助那些寻找简单方法完成工作的人。


但是警告,这不会为你转义标签,正如你在这里看到的(下面显然是行不通的):

textarea残疾> < 这是创建textarea的代码: textarea > < textarea > < / textarea > < /

在HTML ?不。

在XML / XHTML吗?您可以使用CDATA块。