jQuery源码之 empty与html('')的区别

 
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

  1. 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]]);
  2. 删除internalKey(对象标识),push id到deletedIds

  

简单的说empty,首先循环给后代元素移除绑定、清除jquery给此dom的cache,然后循环removeFirstChild。

而html(''),则是简单暴力的设置innerHTML = '';

转自:http://www.cnblogs.com/henryli/archive/2014/02/25/3566461.html

猜你喜欢

转载自www.cnblogs.com/catgatp/p/9498525.html