Handling of special characters in the html method of jquery

When using the html() method of jquery, sometimes the added html code contains some special characters that need to be escaped.

 

The following example:

inst_html = "<a style=color:white' onmouseover = '";  
inst_html += "javascript:showme('"+inst.instId+"_"+valId+"');";  
inst_html += "'  ";  
$("#inst_div_"+valId).html(inst_html);  

 

If it is written directly in this way, there is no problem under chrome and FF browsers, but an error will be reported under IE8.

The solution is to escape the ' in javascript and change it to ', so that no error will be reported.

 

Change it to:

inst_html = "<a style=color:white' onmouseover = '";  
inst_html += "javascript:showme('"+inst.instId+"_"+valId+"');";  
inst_html += "'  ";  
$("#inst_div_"+valId).html(inst_html);  

 

 

var entityMap = {
  '&': '&',
  '<': '<',
  '>': '>',
  '"': '"',
  "'": ''',
  '/': '/',
  '`': '`',
  '=': '='
};

function escapeHtml (string) {
  return String(string).replace(/[&<>"'`=\/]/g, function (s) {
    return entityMap[s];
  });
}

 https://stackoverflow.com/questions/24816/escaping-html-strings-with-jquery

 

When we use the FCK editor to save the information to the database, the saved html is escaped. When we read it and display it on the page, we need to reverse the escaping, otherwise the HTML tag will be displayed. In fact, this series is very simple, the code is as follows:

 

//HTML escape
function HTMLEncode(html){
  var temp = document.createElement ("div");
  (temp.textContent != null) ? (temp.textContent = html) : (temp.innerText = html);
  var output = temp.innerHTML;
  temp = null;
  return output;
}


//HTML reverse escape
function HTMLDecode(text){
  var temp = document.createElement("div");
  temp.innerHTML = text;
  var output = temp.innerText || temp.textContent;
  temp = null;
  return output;
}

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326993076&siteId=291194637