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

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


当前回答

如果你的目标是显示你在同一页面的其他地方执行的代码块,你可以使用textContent(它是纯js和良好的支持:http://caniuse.com/#feat=textcontent)

<div id="myCode">
    <p>
        hello world
    </p>
</div>

<div id="loadHere"></div>


document.getElementById("myCode").textContent = document.getElementById("loadHere").innerHTML;

要在结果中获得多行格式,您需要在目标div上设置css样式“white-space: pre;”,并在每一行的末尾使用“\r\n”单独写入行。

这里是一个演示:https://jsfiddle.net/wphps3od/

与使用textarea相比,这种方法有一个优点:代码不会像在textarea中那样重新格式化。(比如&nbsp;在文本区域中完全删除)

其他回答

我使用<xmp>,就像这样: http://jsfiddle.net/barnameha/hF985/1/

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

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

推荐:

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

下面是几个答案的组合:

函数c(s) { 返回s.split(“& lt;”). join(“<”).split(“在”). join(“>”).split (", ") . join(“&”) } displayMe。innerHTML = ok.innerHTML; console.log ( c (ok.innerHTML) ) <textarea style="display:none" id="ok"> <脚本> console.log(“hello”,5和9); > < /脚本 textarea > < / < div id = " displayMe " > < / div >

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

我是这样做的:

$str = file_get_contents("my-code-file.php");
echo "<textarea disabled='true' style='border: none;background-color:white;'>";
echo $str;
echo "</textarea>";