如何在网页上显示HTML片段,而不需要将每个<替换为<>和>?
换句话说,是否有一个标记表示在点击结束标记之前不呈现HTML ?
如何在网页上显示HTML片段,而不需要将每个<替换为<>和>?
换句话说,是否有一个标记表示在点击结束标记之前不呈现HTML ?
当前回答
你可以试试:
你好!下面是一些代码: < xmp > < div id = "你好" > < / div > < / xmp >
其他回答
它可能并不适用于所有情况,但将代码片段放在文本区域内将它们显示为代码。
如果你不想让它看起来像一个实际的文本区域,你可以用CSS样式文本区域。
//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)
我认为:
你想要编写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: " and &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 </textarea or similar &thing; needs escaping: &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
注意:>从来不需要转义。甚至在正常元素中也没有。
是否有一个标签表示在点击结束标签之前不呈现HTML ?
不,没有。在HTML中,除了转义某些字符外,没有其他方法:
& as & < as <
(顺便说一句,没有必要转义>,但人们经常这样做是为了对称。)
当然,您应该将结果转义的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 >
在HTML ?不。
在XML / XHTML吗?您可以使用CDATA块。