zoukankan      html  css  js  c++  java
  • JavaScript 元素的删除

    在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);
  • 相关阅读:
    VIM 配色方案,先保存一下
    ncurses库的介绍与安装
    win7 设置双屏壁纸
    3. Vim入门教程
    2. Vim 概念扫盲
    把Debian 设置中文环境
    静态代码块和构造代码块的区别
    jsp详解(3个指令、6个动作、9个内置对象、11个隐式对象)
    JVM虚拟机详解
    Java 的内置对象
  • 原文地址:https://www.cnblogs.com/coolicer/p/2749450.html
Copyright © 2011-2022 走看看