参见英文答案 >
What’s the difference between jQuery.fn.empty() and jQuery.fn.html(”)?3
> JavaScript/jQuery html(null) vs html(”)2
在Jquery中有什么区别?
> JavaScript/jQuery html(null) vs html(”)2
在Jquery中有什么区别?
$('#divid').html("");
和
$('#divid').empty();
在jQuery.js内部都做相同的操作吗?
哪一个更好使用.
解决方法
T认为.empty()更快.这是.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; }
而这是jQuery .html(“”)源码:
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; }
很清楚,你可以选择最好的.