鉴于以下HTML,我将如何编码<pre><code class="language-html"></code></pre>
块内的HTML实体? n.b.,在将要使用它的实际页面上有许多这样的块。
<div><strong>Rendered</strong>
<div>This is a div, which contains a <p>p</p> and a <span>span</span>.</div>
</div>
<div><strong>Code</strong>
<pre><code class="language-html">
<div>This is a div, which contains a <p>p</p> and a <span>span</span>.</div>
</code></pre>
</div>
目标是使此输出具有以下内容:
这是一个div,其中包含一个 p 和跨度。
<div>This is a div, which contains a <p>p</p> and a <span>span</span>.</div>
(即,代码的第一个副本应该呈现,而第二个应该仅显示。)
修改 (2016年2月14日): HTML-encoding lost when attribute read from input field解决了一个稍微不同的问题,因此,这不是重复的。
答案 0 :(得分:1)
一个简单的解决方案是抓住html()
,然后将其设为text()
:
$('pre > code.language-html').text(function() {
$(this).text($(this).html());
})
// or simpler
//$('pre > code.language-html').text(function() { return $(this).html(); })
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div>This is a div, which contains a <p>p</p> and a <span>span</span>.</div>
<div><pre><code class="language-html">
<div>This is a div, which contains a <p>p</p> and a <span>span</span>.</div>
</code></pre></div>
<div><pre><code class="language-html">
<div>This is a div, which contains a <p>p</p> and a <span>span</span>.</div>
</code></pre></div>
&#13;