在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);