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

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


当前回答

我认为:

你想要编写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

 

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

其他回答

这是目前为止在大多数情况下最好的方法:

<pre><code>
    code here, escape it yourself.
</code></pre>

我会投票给第一个提出这个建议的人,但我没有名气。为了那些试图在网上找到答案的人,我不得不说些什么。

在HTML中有几种方法可以转义所有内容,但都不是很好。

或者你可以放入一个iframe来加载一个普通的旧文本文件。

你可以试试:

你好!下面是一些代码: < xmp > < div id = "你好" > < / div > < / xmp >

已弃用,但适用于FF3和IE8。

<xmp>
   <b>bold</b><ul><li>list item</li></ul>
</xmp>

推荐:

<pre><code>
    code here, escape it yourself.
</code></pre>
 //To show xml tags in table columns you will have to encode the tags first

function htmlEncode(value) {
    //create a in-memory div, set it's inner text(which jQuery automatically encodes)
    //then grab the encoded contents back out.  The div never exists on the page.
    return $('<div/>').text(value).html();
}

html = htmlEncode(html)