jQuery.fn.empty()和jQuery.fn.html('')之间有什么区别?

Tom*_*man 34 jquery

两者之间有什么区别吗?

$("#header").empty()
Run Code Online (Sandbox Code Playgroud)

$("#header").html('')
Run Code Online (Sandbox Code Playgroud)

另外,我应该使用哪个?$("#header").empty()更具可读性,但有什么比这更快的$("#header").html('')

Mat*_*all 39

两者之间没有功能差异.使用,.empty()因为它更短(更简洁),更易读.

不要担心性能差异.请记住,jQuery没有被使用,因为它比vanilla JavaScript 运行得更快 - 它被使用,因为它编写得更快.开发人员的时间远远超过处理器时间.

已经有一个jsPerf来比较相对性能:http://jsperf.com/jquery-empty-vs-html .每个测试用例都表明.empty()速度更快.


直接来自jQuery源:

empty: function() {
    for ( var i = 0, elem; (elem = this[i]) != null; i++ ) {
        // Remove element nodes and prevent memory leaks
        if ( elem.nodeType === 1 ) {
            jQuery.cleanData( elem.getElementsByTagName("*") );
        }

        // Remove any remaining nodes
        while ( elem.firstChild ) {
            elem.removeChild( elem.firstChild );
        }
    }

    return this;
},

html: function( value ) {
    if ( value === undefined ) {
        return this[0] && this[0].nodeType === 1 ?
            this[0].innerHTML.replace(rinlinejQuery, "") :
            null;

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

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

        try {
            for ( var i = 0, l = this.length; i < l; i++ ) {
                // Remove element nodes and prevent memory leaks
                if ( this[i].nodeType === 1 ) {
                    jQuery.cleanData( this[i].getElementsByTagName("*") );
                    this[i].innerHTML = value;
                }
            }

        // If using innerHTML throws an exception, use the fallback method
        } catch(e) {
            this.empty().append( value );
        }

    } else if ( jQuery.isFunction( value ) ) {
        this.each(function(i){
            var self = jQuery( this );

            self.html( value.call(this, i, self.html()) );
        });

    } else {
        this.empty().append( value );
    }

    return this;
},
Run Code Online (Sandbox Code Playgroud)

.empty()不必处理检查不同的可能参数类型; 它可以直接淘汰DOM元素.

  • "开发人员的时间远远超过处理器时间." - 直到应用程序运行明显缓慢:) (16认同)
  • 这是用户时间,而不是处理器时间. (6认同)