欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

清空元素html("") innerHTML="" 与 empty()的区别和应用(推荐)

程序员文章站 2022-11-25 11:50:32
一、清空元素的区别      1、错误做法一:       &nbs...

一、清空元素的区别

     1、错误做法一:

           $("#test").html("");//该做法会导致内存泄露

     2、错误做法二:

           $("#test")[0].innerhtml="";  ;//该做法会导致内存泄露

     3、正确做法:

        //$("#test").empty();       

二、原理:

在 jquery 中用 innerhtml 的方法来清空元素,是必然会导致内存泄露的,由于 jquery 对于同一元素多事件处理没有直接采用浏览器事件模型,而是自己缓存事件,遍历触发,以及便于 trigger 程序触发 :

// init the element's event structure 
 var events = jquery.data(elem, "events") || jquery.data(elem, "events", {}), 
  handle = jquery.data(elem, "handle") || jquery.data(elem, "handle", function(){ 
  // handle the second event of a trigger and when 
  // an event is called after a page has unloaded 
  return typeof jquery !== "undefined" && !jquery.event.triggered ? 
   jquery.event.handle.apply(arguments.callee.elem, arguments) : 
   undefined; 
  }); 

采用 data 方法,将一些数据关联到了元素上面,上述事件即是采用该机制缓存事件监听器。

那么就可以知道,直接 innerhtml=“” 而不通知 jquery 清空与将要删除元素关联的数据,那么这部分数据就再也释放不了了,即为内存泄露。

remove: function( selector ) { 
 if ( !selector || jquery.filter( selector, [ this ] ).length ) { 
  // prevent memory leaks 
  jquery( "*", this ).add([this]).each(function(){ 
  jquery.event.remove(this); 
  jquery.removedata(this); 
  }); 
  if (this.parentnode) 
  this.parentnode.removechild( this ); 
 } 
 }, 
 empty: function() { 
 // remove element nodes and prevent memory leaks 
 jquery(this).children().remove(); 
 
 // remove any remaining nodes 
 while ( this.firstchild ) 
  this.removechild( this.firstchild ); 
 }

  以上就是小编为大家整理的清空元素html("")、innerhtml="" 与 empty()的区别和应用的全部内容啦~希望能够帮助到各位朋友~~