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

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


当前回答

示例1:

<pre>
  This text has
  been formatted using
  the HTML pre tag. The brower should
  display all white space
  as it was entered.
</pre>

示例2:

<pre>
  <code>
    My pre-formatted code
    here.
  </code>
</pre>

示例3: (如果你实际上是在“引用”一段代码,那么标记应该是)

<blockquote>
  <pre>
    <code>
        My pre-formatted "quoted" code here.
    </code>
  </pre>
</blockquote>

其他回答

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

我很久以前用过这个,它对我很有用,我希望它也能帮助到你。

var preTag = document.querySelectorAll('pre'); console.log(preTag.innerHTML); for (var i = 0; i < preTag.length; i++) { var pattern = preTag[i].innerHTML; pattern = pattern.replace(/&lt;/g, “&lt;”).replace(/&gt;/g, “&gt;”); 控制台.log(模式); preTag[i].innerHTML = pattern; } <pre> <p>例</p> <span>更多文字</span> </pre>

这是一个简单的技巧,我已经在Safari和Firefox中尝试过了

<code>
    <span><</span>meta property="og:title" content="A very fine cuisine" /><br>
    <span><</span>meta property="og:image" content="http://www.example.com/image.png" />
</code>

它将显示如下:

你可以在这里现场观看

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

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

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

它可能并不适用于所有情况,但将代码片段放在文本区域内将它们显示为代码。

如果你不想让它看起来像一个实际的文本区域,你可以用CSS样式文本区域。