分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > 前端开发

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

发布时间:2023-09-06 02:10责任编辑:胡小海关键词:jQuery
 
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

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

原文地址:https://www.cnblogs.com/catgatp/p/9498525.html

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved