[JS][jQuery]清空元素html("")、innerHTML="" 與 empty()的區別:關於內容泄露問題

來源:互聯網
上載者:User

[JS][jQuery]清空元素html("")、innerHTML="" 與 empty()的區別:關於內容泄露問題

清空元素html("")、innerHTML="" 與 empty()的區別


一、清空元素的區別     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 ); }

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.