JavaScript 元素的刪除

來源:互聯網
上載者:User

在DOM操作中,有一個removeChild的方法。但是我們要知道,即使是這樣從DOM中刪除了,它們還是存在的。那它們會產生什麼問題呢?一個嚴重的問題是,那些刪除的節點都存在記憶體中,這就是傳說中的記憶體泄露。如果幾十兆,幾百的時候就會影響瀏覽器的運行了。(- - 其實我是沒有測試過的)

所以我是知道,不能隨便地刪除元素節點。我之前用的是一個沒什麼用的方法。將它先設定display為node,再刪除。感覺就是先把衣服脫掉再殺死你?

JQ有一個remove方法,我覺得應該是考慮全面的,不知道有沒有人告訴它會不會引起記憶體問題?

在網上看到一個方法,就是動態建立一個空的元素,把要刪除的節點丟到這個元素,再清空裡面的內容,這樣可以從記憶體中清除掉。

var garbageBin;window.onload = function ()    {    if (typeof(garbageBin) === 'undefined')        {        //Here we are creating a 'garbage bin' object to temporarily         //store elements that are to be discarded        garbageBin = document.createElement('div');        garbageBin.style.display = 'none'; //Make sure it is not displayed        document.body.appendChild(garbageBin);        }    function discardElement(element)        {        //The way this works is due to the phenomenon whereby child nodes        //of an object with it's innerHTML emptied are removed from memory        //Move the element to the garbage bin element        garbageBin.appendChild(element);        //Empty the garbage bin        garbageBin.innerHTML = "";        }    }//To use it in your context, you would do it like this:discardElement(this);
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.