Prevent jQuery from escaping html entities

2019-06-15 12:23发布

问题:

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