innerHTML vs jQuery .html() 有什么分别?

根据jQuery官方文件所提及.html()是使用 This method uses the browser's innerHTML property,既然使用的是相同方法,为何结果不一样?

<head>
    <script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
    <script src="http://crypto-js.googlecode.com/svn/tags/3.1.2/build/rollups/md5.js"></script>
    <script>
    
        var md5 = document.getElementById("md5").value;
        var hash = CryptoJS.MD5(md5);
        
        document.getElementById("showMD5").innerHTML = hash; //能传正确的值
        $("#showMD5").html(hash); //没反应
        
    </script>
</head>
<body>
    <input type="text" id="md5">
    <button id="btn" onclick="chkMd5()">Check MD5</button>
    <div id="showMD5"></div>
</body>

另外jQuery中.text() .html()有什么分别?

console.log($("#showMD5").html()); 
console.log($("#showMD5").text()); //.html() .text()得出相同结果
阅读 3.9k
1 个回答

jquery-1.11.3html的实现方式:

html: function( value ) {
        return access( this, function( value ) {
            var elem = this[ 0 ] || {},
                i = 0,
                l = this.length;

            if ( value === undefined ) {
                return elem.nodeType === 1 ?
                    elem.innerHTML.replace( rinlinejQuery, "" ) :
                    undefined;
            }

            // See if we can take a shortcut and just use innerHTML
            if ( typeof value === "string" && !rnoInnerhtml.test( value ) &&
                ( support.htmlSerialize || !rnoshimcache.test( value )  ) &&
                ( support.leadingWhitespace || !rleadingWhitespace.test( value ) ) &&
                !wrapMap[ (rtagName.exec( value ) || [ "", "" ])[ 1 ].toLowerCase() ] ) {

                value = value.replace( rxhtmlTag, "<$1></$2>" );

                try {
                    for (; i < l; i++ ) {
                        // Remove element nodes and prevent memory leaks
                        elem = this[i] || {};
                        if ( elem.nodeType === 1 ) {
                            jQuery.cleanData( getAll( elem, false ) );
                            elem.innerHTML = value;
                        }
                    }

                    elem = 0;

                // If using innerHTML throws an exception, use the fallback method
                } catch(e) {}
            }

            if ( elem ) {
                this.empty().append( value );
            }
        }, null, value, arguments.length );
    }
推荐问题
宣传栏