zoukankan      html  css  js  c++  java
  • 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
    View Code

    将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 = '';

  • 相关阅读:
    【Linux】- 文件基本属性
    【Linux】- mv命令
    【Linux】- 守护进程supervisor安装使用
    【Linux】- rm命令
    【Linux】- 开启远程连接
    【Redis】- 安装为windows服务
    Apache2.4 与 php7.1.6的链接
    apache2.4 的安装
    MySQL v5.7.18 版本解压安装
    网站系统消息表设计
  • 原文地址:https://www.cnblogs.com/henryli/p/3566461.html
Copyright © 2011-2022 走看看