Javascript / jQuery - convert special html characters

匿名 (未验证) 提交于 2019-12-03 02:52:02

问题:

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

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.

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?

回答1:

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.



回答2:

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

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

jQuery:

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

example: 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.



易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!