0
var wText = "What's on your mind ?";
var dCreate = "<div class='createpost-sec'><textarea class='clicktxt' rows='1' cols='1' placeholder='"+wText+"'/>"+dClear+"</div></div></div>";

当我在文本丢失html后追加时',请帮助我如何中和'字符

4

1 回答 1

1

您需要对 html 的字符串进行编码。例如,单引号应该是&#39;.:

jQuery解决方案:

function htmlEncode(value){
  //create a in-memory div, set it's inner text(which jQuery automatically encodes)
  //then grab the encoded contents back out.  The div never exists on the page.
  return $('<div/>').text(value).html();
}

function htmlDecode(value){
  return $('<div/>').html(value).text();
}

手动解决方案:

function htmlEscape(str) {
    return String(str)
            .replace(/&/g, '&amp;')
            .replace(/"/g, '&quot;')
            .replace(/'/g, '&#39;')
            .replace(/</g, '&lt;')
            .replace(/>/g, '&gt;');
}

function htmlUnescape(value){
    return String(value)
        .replace(/&quot;/g, '"')
        .replace(/&#39;/g, "'")
        .replace(/&lt;/g, '<')
        .replace(/&gt;/g, '>')
        .replace(/&amp;/g, '&');
}

资源。

于 2013-09-07T11:01:26.393 回答