Prevent jQuery from escaping html entities

倖福魔咒の 提交于 2019-12-08 15:00:42

问题


I have some simple html editor. Let's say that user types following:

<p>Ok, this just &amp; sucks :) &ndash;</p>

and it is saved to some variable:

var content = "<p>Ok, this just &amp; sucks :) &ndash;</p>";

Now, somewhere I'm using jQuery to append this text to some element:

$(this).html(content); // where content is the string above

The problem is that it is escaped:

<p>Ok, this just &amp;amp; sucks :) &amp;ndash;</p>

How can I achieve to have the exact string with &amp ; and &ndash ; and also to have < and not &lt ; because I need html tags?

Edit: more details added


回答1:


The problem is not that jQuery is escaping the entities. I think if you use console.log to write the content string, you'll see that your editor is returning escaped entities to you.

The whole point of .html() vs .text() is that .html() is for HTML that will be treated as HTML.




回答2:


I Guess you want to have the text <p>Ok, this just &amp;amp; sucks :) &amp;ndash;</p> to be exactly shown with out converting them, so that the &amp; and ndash; will not be converted to & and -, then use :

$(this).text(content);

One problem with this is that the content will be added as a text in site the this element. It will not create a p element and append it to this.

But if you want to take the effect of conversion then you code should work.

One more thing I want to mention, I believe that language is not the only one related to those conversion. Browser take the main role in those cases. SO, What ever we do in the script if browser get another chance to check the contents it will convert them to & and -.



来源:https://stackoverflow.com/questions/7773553/prevent-jquery-from-escaping-html-entities

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