HTML-encoding lost when attribute read from input field

前端 未结 25 3811
时光说笑
时光说笑 2020-11-21 04:04

I’m using JavaScript to pull a value out from a hidden field and display it in a textbox. The value in the hidden field is encoded.

For example,



        
25条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-21 04:48

    Here's a non-jQuery version that is considerably faster than both the jQuery .html() version and the .replace() version. This preserves all whitespace, but like the jQuery version, doesn't handle quotes.

    function htmlEncode( html ) {
        return document.createElement( 'a' ).appendChild( 
            document.createTextNode( html ) ).parentNode.innerHTML;
    };
    

    Speed: http://jsperf.com/htmlencoderegex/17

    speed test

    Demo:

    Output:

    output

    Script:

    function htmlEncode( html ) {
        return document.createElement( 'a' ).appendChild( 
            document.createTextNode( html ) ).parentNode.innerHTML;
    };
    
    function htmlDecode( html ) {
        var a = document.createElement( 'a' ); a.innerHTML = html;
        return a.textContent;
    };
    
    document.getElementById( 'text' ).value = htmlEncode( document.getElementById( 'hidden' ).value );
    
    //sanity check
    var html = '
    & hello
    '; document.getElementById( 'same' ).textContent = 'html === htmlDecode( htmlEncode( html ) ): ' + ( html === htmlDecode( htmlEncode( html ) ) );

    HTML:

    
    
    

提交回复
热议问题