博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[JS][jQuery]清空元素html("")、innerHTML="" 与 empty()的差别:关于内容泄露问题...
阅读量:7192 次
发布时间:2019-06-29

本文共 1362 字,大约阅读时间需要 4 分钟。

清空元素html("")、innerHTML="" 与 empty()的差别

一、清空元素的差别     1、错误做法一:           $("#test").html("");//该做法会导致内存泄露
2、错误做法二:           $("#test")[0].innerHTML="";  ;//该做法会导致内存泄露
3、正确做法:
       //$("#test").empty();

二、原理:

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

  1. // Init the element's event structure  
  2.         var events = jQuery.data(elem, "events") || jQuery.data(elem, "events", {}),  
  3.             handle = jQuery.data(elem, "handle") || jQuery.data(elem, "handle"function(){  
  4.                 // Handle the second event of a trigger and when  
  5.                 // an event is called after a page has unloaded  
  6.                 return typeof jQuery !== "undefined" && !jQuery.event.triggered ?

      

  7.                     jQuery.event.handle.apply(arguments.callee.elem, arguments) :  
  8.                     undefined;  
  9.             });  

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

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

  1. remove: function( selector ) {  
  2.         if ( !selector || jQuery.filter( selector, [ this ] ).length ) {  
  3.             // Prevent memory leaks  
  4.             jQuery( "*"this ).add([this]).each(function(){  
  5.                 jQuery.event.remove(this);  
  6.                 jQuery.removeData(this);  
  7.             });  
  8.             if (this.parentNode)  
  9.                 this.parentNode.removeChild( this );  
  10.         }  
  11.     },  
  12.   
  13.     empty: function() {  
  14.         // Remove element nodes and prevent memory leaks  
  15.         jQuery(this).children().remove();  
  16.   
  17.         // Remove any remaining nodes  
  18.         while ( this.firstChild )  
  19.             this.removeChild( this.firstChild );  
  20.     }  

转载地址:http://fmtkm.baihongyu.com/

你可能感兴趣的文章
LeetCode-二叉树的最大深度
查看>>
Linux内核剖析(五)Linux内核的构建过程
查看>>
19、生鲜电商平台-安全设计与架构
查看>>
webpack常见的配置总结 ---只是一些常见的配置
查看>>
Django_06_项目完成
查看>>
寻找子字符串int find_substr(char *s1, char *s2)
查看>>
apache配置文件参数优化
查看>>
Manifest.xml中不要出现重复的uses-permission声明
查看>>
UFS文件系统简明学习笔记
查看>>
详解Redis 的持久化机制--RDB和AOF
查看>>
就算神游 之四:富士山和富士游乐园 9
查看>>
linux 学习 12 服务管理
查看>>
maven全局配置文件settings.xml详解
查看>>
模型图纸数据库设计
查看>>
Two classes have the same XML type name 排错【转】
查看>>
linux笔记:linux常用命令-关机重启命令
查看>>
想要提高网页转换率?试试这16个UI秘诀
查看>>
转)VCSA 6.5重启无法访问,报错“503 Service Unavailable”的解决方法
查看>>
Configuring and troubleshooting a Schema Provider
查看>>
Windows环境安装MySQL数据库
查看>>