質問

I need to render html content as html, but it is rendering as string text.

$('#description').html($.parseHTML('<%=event.description%>'));

jQuery add the text as string, it is not rendering the HTML tags, if blog.description contains paragraph, bold, italic and other HTML elements it renders in pure text.

Description content is not stored as escaped HTML, is just in pure HTML.

Thanks in advance

## EDIT ##

I'm not using .NET Framework, just Node.JS with Express and EJS template engine.

I store the description field in DB as both methods:

:: Decoded:

"<p> example <b>text</b> </p>"

:: Undecoded:

"&lt;p&gt; example &lt;b&gt;text&lt;&#x2F;b&gt; &lt;&#x2F;p&gt;"

Unfortunately both ways don't make the text to be correctly displayed as HTML into signed div.

I resorted to jQuery because the first attempt to load the text directly from DB didn't work.

I've tried:

$('#description').html( MY TEXT ).text();

$('#description').text( MY TEXT ).html();

$('#description').html( $.parseHTML(MY TEXT) );

Doesn't work. However if I get the description text and copy and make it render by myself (avoiding DB) it displays correctly.

The picture shows what is going on:

enter image description here

Any extra tip will be helpful.

役に立ちましたか?

解決

I still believe that issue is with your text being HTML encoded in your DB and somewhere along the way back, and you need to decode before displaying on screen. Unfortunately I do not know node.js and what the equivalent method for WebUtility.HtmlDecode() in .Net is. (Hopefully someone else can answer this for you).

As a hack, you can do the following, but I would not recommend it, it is a workaround at best:

Encode or Decode HTML entities with jQuery

var mytext = '<%=event.description%>';
var decoded = $('<div />').html(mytext).text();
$('#description').html(decoded);

jsFiddle demo

他のヒント

Try as follows.

$('#description').html($('<%=event.description%>'));

If you are trying to assign it as html to element, you not need to parse it as html. It will automatically be parsed but if you setting it as text and want to assign html there you need parsing.

so try this:

$('#description').html('<%=event.description%>');
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top