jQuery源碼之 empty與html('')的區別
阿新 • • 發佈:2018-08-18
重復 頁面 emp .get delete .com for nod lba
empty: function() {
var elem,
i = 0;
for ( ; (elem = this[i]) != null; i++ ) {
// Remove element nodes and prevent memory leaks
if ( elem.nodeType === 1 ) {
//循環清除Data數據
jQuery.cleanData( getAll( elem, false ) );
}
// 移除child
while ( elem.firstChild ) {
elem.removeChild( elem.firstChild );
}
// If this is a select, ensure that it displays empty (#12336)
// Support: IE<9
if ( elem.options && jQuery.nodeName( elem, "select" ) ) {
elem.options.length = 0;
}
}
return this;
},
代碼中,首先清除了所有的data數據,那麽data都包含哪些內容呢?
getALl方法查找到到所有後代元素。jquery的getAll代碼如下:
var strundefined = typeof undefined;
function getAll( context, tag ) {
var elems, elem,
i = 0,
found = typeof context.getElementsByTagName !== strundefined ? context.getElementsByTagName( tag || "*" ) :
typeof context.querySelectorAll !== strundefined ? context.querySelectorAll( tag || "*" ) :
undefined;
if ( !found ) {
for ( found = [], elems = context.childNodes || context; (elem = elems[i]) != null; i++ ) {
if ( !tag || jQuery.nodeName( elem, tag ) ) {
found.push( elem );
} else {
jQuery.merge( found, getAll( elem, tag ) );
}
}
}
return tag === undefined || tag && jQuery.nodeName( context, tag ) ?
jQuery.merge( [ context ], found ) :
found;
}
getAll(document.body,false);// HTMLCollection Array
將getALl取到的集合, cleanData
- removeEvent 解除事件,釋放內存 (jquery綁定的事件保存在data中),代碼如下,可以找到我們綁定的事件列表。//expando是頁面中不重復的jquery每個對象的標識。expando: "jQuery" + ( version + Math.random() ).replace( /\D/g, "" ),
$(‘body‘).on(‘click‘,function(){ alert(‘this is body‘); }); console.log($.cache[$(‘body‘)[0][$.expando]]);
- 刪除internalKey(對象標識),push id到deletedIds
簡單的說empty,首先循環給後代元素移除綁定、清除jquery給此dom的cache,然後循環removeFirstChild。
而html(‘‘),則是簡單暴力的設置innerHTML = ‘‘;
轉自:http://www.cnblogs.com/henryli/archive/2014/02/25/3566461.html
jQuery源碼之 empty與html('')的區別