开发者

How do I escape html in the "innerHtml" property with javascript?

开发者 https://www.devze.com 2023-03-28 10:43 出处:网络
I have a combo of javascript and my jsp that is adding some text and escaping it.I also have some javascrpt that will allow me to edit the text after it has been submitted.However the html renders whe

I have a combo of javascript and my jsp that is adding some text and escaping it. I also have some javascrpt that will allow me to edit the text after it has been submitted. However the html renders when Click the edit button.

    function editCommentToggle( id )
{
    theRow = document.getElementById("id"+id);
    //user = theRow.cells[0].innerHTML;
    //date = theRow.cells[1].innerHTML;
 -->   com = theRow.cells[2].innerHTML;


    idx = 2;
    maxlength = 250;

   开发者_StackOverflow中文版             // Comment field
        cell = theRow.cells[idx];
        while( cell.childNodes.length > 0 ) cell.removeChild(cell.childNodes[0]);
        element = document.createElement("textarea");
        element.id="comments-"+id;
        element.rows="3";
        element.value = com;
        element.style.width = "400px";
        element.maxLength = "250";
        element.onfocus = element.onkeydown = element.onkeyup = function(){return characterCounterEdit(undefined, maxlength, this);}; 
        cell.appendChild(element);

"theRow.cells[2].innerHTML;" is grabbing the text or html in that cell, but if say there is a 'newline' it displays a<br>.....how should I structure this to preserve the escaped html??

thanx


Use textContent (or innerText in IE)

com = theRow.cells[2].textContent || theRow.cells[2].innerText


I had an old web application, no jQuery or other fancy libraries available. I tried if-then-else textContent/innerText fix but some reason did not work for dynamically created DIV element. So had to implement this alternative fix. Tested on Firefox, IE8, IE9 and Opera.

// XMLEscape reserverd characters
function XMLEscape(sValue, bUseApos) {
  var sval="";
  for(var idx=0; idx < sValue.length; idx++) {
    var c = sValue.charAt(idx);
    if      (c == '<') sval += "&lt;";
    else if (c == '>') sval += "&gt;";
    else if (c == '&') sval += "&amp;";
    else if (c == '"') sval += "&quot;";
    else if (c == '\'') sval += (bUseApos ? "&apos;" : "&#39;");
    else sval += c;
  }
  return sval;
}

var sprite = document.createElement("DIV");
sprite.setAttribute("class", "sprite_red");
sprite.setAttribute("style", "top:" + nextOffsetTop +"px");
sprite.innerHTML = XMLEscape(items[idx]);
scene.append(sprite);
0

精彩评论

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