zoukankan      html  css  js  c++  java
  • javascript / js / jquery的HtmlEncode

    1.首先,javascript / js / jquery 没有 HtmlEncode 方法。

    2.其次,如果是想给页面元素赋值,防止跨站攻击,可以对其innerText进行赋值,而不要对innerHTML赋值。

        xx.innerText = str 相当于 xx.innerHTML = HtmlEncode( str );

    3.如果一定要一个HtmlEncode方法,可以参见:

       http://stackoverflow.com/questions/1219860/javascript-jquery-html-encoding

     1 function htmlEncode( html ) {
     2     return document.createElement( 'a' ).appendChild( 
     3         document.createTextNode( html ) ).parentNode.innerHTML;
     4 };
     5 
     6 function htmlDecode( html ) {
     7     var a = document.createElement( 'a' ); a.innerHTML = html;
     8     return a.textContent;
     9 };
    10 
    11 function htmlEncodeX(value){
    12   //create a in-memory div, set it's inner text(which jQuery automatically encodes)
    13   //then grab the encoded contents back out.  The div never exists on the page.
    14   return $('<div/>').text(value).html();
    15 }
    16 
    17 function htmlDecodeX(value){
    18   return $('<div/>').html(value).text();
    19 }
    20 
    21 var str = "<p>\t Hi \n There22 </p>";
    22 var s1 = htmlEncodeX( str );
    23 var s2 = htmlDecodeX( s1 );
    24 alert( str );
    25 alert( str == s2 );

    测试位置:

    http://jsfiddle.net/ThinkingStiff/FSaU2/

    测试方法:把上面那段代码,覆盖到网址的左下框(javascript),然后点上方的Run按钮。带X的版本,无法在那个网页里运行,但本地测试,目前还遇到问题。不带X的版本,可以在那个网页里运行,而且本地运行也没问题。

  • 相关阅读:
    统计:概述
    概率论总结
    概率论13 中心极限定律
    概率论12 矩与矩生成函数
    概率论11 协方差与相关系数
    概率论10 方差与标准差
    概率论09 期望
    概率论08 随机变量的函数
    mysql 分区
    Linux 搭建svn版本库
  • 原文地址:https://www.cnblogs.com/xxxteam/p/3024151.html
Copyright © 2011-2022 走看看