开发者

Javascript - using innerHTML to output strings *WITHOUT* HTML-encoded special characters?

It appears that JavaScript auto-converts certain special characters into HTML entities when outputting content via the innerHTML() function. This is a problem, since I need to be able to output < and > without converting to gt; and lt;

Can this auto-conversion be prevented, reversed, or escaped? So far, no matter what I do, < and > are always automatically encoded into HTML entities.

Example code:

function DisplayQueries() {
    var IDs = ['AllOpenedINC','AllOpene开发者_Go百科dCRQ','AllClosedINC','AllClosedCRQ','SameDayINC','SameDayCRQ','NotSameDayINC','NotSameDayCRQ',
        'StillOpenINC','StillOpenCRQ','OpenOldINC','OpenOldCRQ','OtherQueuesINC','OtherQueuesCRQ']

    for (var i = 0; i < IDs.length; i++) {
        if (eval(IDs[i]))
            document.getElementById(IDs[i]).innerHTML = eval(IDs[i]);
    }
}

Example query variable:

AllOpenedINC = "('Company*+' = \"test\" OR 'Summary*' = \"%test%\") AND ('Submit Date' >= \"" + theDate +
    " 12:00:00 AM\" AND 'Submit Date' <= \"" + theDate + " 11:59:59 PM\")" + nameINC;


You should focus on what you want to accomplish as a result, rather than the way of doing it. innerHTML() does encode, innerText() and textContent() do encoding too. So you should decode your strings if you want them as < or > back.

You can use this unescapeHTML() function to get your results as you want them.

 function unescapeHTML() {
    return this.stripTags().replace(/&lt;/g,'<').replace(/&gt;/g,'>').replace(/&amp;/g,'&');
  }

I hope this helps. I've copied it from Prototype.


I think your question is based on a false premise. Just make a very simple test:

document.getElementById("testdiv").innerHTML = '<h1><em>Hello</em></h1>';

if this works fine then the problem is not on the JS side, instead you use some other components in your system which HTML-encode your characters.


I figured out what's going on. There's no easy way to prevent innerHTML from converting special characters to HTML entities, but since the problem was surfacing when copying the content of a DIV to the clipboard (using IE-only JS, which works since this is in a government environment where everyone has to use IE), I just used the replace() function to re-convert the HTML entities back to < and >.


You can use jquery and .append()

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜