如何将HTML插入为文本 [英] How to insert HTML as Text
问题描述
我想要HTML,例如< p>
,以纯文本显示show,并且不会被浏览器解释为实际标记。
我知道JQuery有.html和.text,但是这是如何在原始JS中完成的?
是编码< p>
到%3Cp%3E
的encodeURIComponent函数,但是如果我只是把它放到HTML中,它将其解释为字面意义上的%3Cp%3E
。 因此,也有类似于 & gt;
和& lt;
,它们可以正常工作,但是我找不到任何能够逃脱&
有没有正确的方式将HTML显示为带有原始JavaScript的文本? 方案
没有必要逃避角色。只需使用 createTextNode
:
var text = document.createTextNode('< p为H.;东西< / p为H.');
document.body.appendChild(text);
在这里查看一个工作示例: http://jsfiddle.net/tZ3Xj/ 。
这正是jQuery如何做的( jQuery 1.5.2的第43行):
返回this.empty()。append((this [0]&& this [0] .ownerDocument || document).createTextNode(text) );
I want HTML, for example, <p>
, to show show as just that, in plain text, and not interpreted by the browser as an actual tag.
I know JQuery has .html and .text, but how is this done in raw JS?
There are functions like encodeURIComponent that encodes <p>
to %3Cp%3E
but if I just put that into HTML, it interprets it literally as %3Cp%3E
.
So there are also things like >
and <
, they work but I can't find any JavaScript functions that escapes & unescapes from this.
Is there a correct way to show HTML as text with raw JavaScript?
There's no need to escape the characters. Simply use createTextNode
:
var text = document.createTextNode('<p>Stuff</p>');
document.body.appendChild(text);
See a working example here: http://jsfiddle.net/tZ3Xj/.
This is exactly how jQuery does it (line 43 of jQuery 1.5.2):
return this.empty().append( (this[0] && this[0].ownerDocument || document).createTextNode( text ) );
这篇关于如何将HTML插入为文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!