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

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


当前回答

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

其他回答

<code><?php $str='&lt;';echo htmlentities($str);?></code>

我发现这是最简单、最快和最紧凑的方法。

是否有一个标签表示在点击结束标签之前不呈现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 >

我是这样做的:

$str = file_get_contents("my-code-file.php");
echo "<textarea disabled='true' style='border: none;background-color:white;'>";
echo $str;
echo "</textarea>";
function escapeHTML(string)
    { 
        var pre = document.createElement('pre');
        var text = document.createTextNode(string);
        pre.appendChild(text);
        return pre.innerHTML;
}//end escapeHTML

它将返回转义的Html

在HTML ?不。

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