html字符串转义,常用于输入框过滤

2016-11-22  本文已影响0人  一个小小实习生
<input type="text" tabindex="0" autofocus="true" id="text"/>
  <div class="farther">
    <div class="son"></div>
    <div class="son"></div>
  </div>
  <div id="div1"></div>
<script type="text/javascript">

String.prototype.encodeHtml = function(){
    return this.replace(/"|&|'|<|>|[\x00-\x20]|[\x7F-\xFF]|[\u0100-\u2700]/g,function($0){
            var c = $0.charCodeAt(0), r = ["&#"];
            c = (c == 0x20) ? 0xA0 : c;
            r.push(c); r.push(";");
            return r.join("");
    });
}
    var dic = document.getElementById('div1');
    var text = document.getElementById('text');
    document.body.onclick = function(){
        dic.innerHTML = text.value.encodeHtml();
    }
</script>
上一篇 下一篇

猜你喜欢

热点阅读