Javascript / jQuery - 转换特殊的 html 字符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3330345/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 04:11:48  来源:igfitidea点击:

Javascript / jQuery - convert special html characters

javascriptjqueryhtml

提问by Alex

I have a preelement with some html code in it. the code has special characters in it, like <, so it doesn't break the page.

我有一个pre包含一些 html 代码的元素。代码中包含特殊字符,例如<,因此不会破坏页面。

Then I have a javascript function that gets the contents of this pre element, highlights it (with codemirror), and replaces the element contents with the highlighted text.

然后我有一个 javascript 函数,它获取这个 pre 元素的内容,突出显示它(使用 codemirror),并用突出显示的文本替换元素内容。

I'm using $("pre").append(...);to do this. The problem is that after the highlighting, on the screen I see &lt;instead of <. How can I convert these characters back to html?

我是$("pre").append(...);用来做这个的。问题是突出显示后,在屏幕上我看到&lt;而不是<. 如何将这些字符转换回 html?

回答by Matthew Manela

You should be using the .text() method to grab the code from the pre. This way you are't giving the encoded symbols to the code highlighter.

您应该使用 .text() 方法从 pre 中获取代码。这样您就不会将编码符号提供给代码荧光笔。

回答by jAndy

I don't know what happens (and why it happens) to your html, but you can use jQuerys .text()and .html()to decode/encode html entitiys like:

我不知道会发生什么(和为什么它会发生)到你的HTML,但你可以使用jQuerys.text().html()解码/编码的HTML entitiys这样的:

HTML

HTML

<div id="test">&lt;&lt;</div>

jQuery:

jQuery:

var t = $('#test');
t.html(t.text()); // will print "<<"

example: http://www.jsfiddle.net/fphw3

示例:http: //www.jsfiddle.net/fphw3

update

更新

Since you mentioned that you use .html()to read the value of your element, a call to .text()instead should solve your issue.

由于您提到您.html()用来读取元素的值,因此调用.text()代替 应该可以解决您的问题。