2016-05-03 224 views
0

我已经创建了一个HTML页面来了解如何移除元素。'remove'和'removeChild'方法有什么区别?

代码:

<html> 
    <head> 
    <script> 
     var childDiv = null; 
     var parent1 = null; 
     var parent2 = null; 
     function init() { 
     childDiv = document.getElementById("child"); 
     parent1 = document.getElementById("parent1"); 
     parent2 = document.getElementById("parent2"); 
     } 

     function rem() { 
     if (childDiv) { 
      childDiv.remove(); 
      alert("child removed"); 
     } else { 
      alert("child does not exist"); 
     } 
     } 

     function remChild() { 
     if (childDiv){ 
      if (parent1.children.length > 0) { 
      parent1.removeChild(childDiv); 
      alert("child unbound from parent"); 
      } else { 
      alert("child exists but is not bound to parent"); 
      } 
     } else { 
      alert("child does not exist"); 

     } 
     } 

     function ins() { 
     if (childDiv) { 
      parent2.appendChild(childDiv); 

      alert("child inserted to another parent"); 
     } 
     } 
    </script> 
    </head> 
    <body onload="init()"> 
    <div id="parent1"> 
     <div id="child"></div> 
    </div> 
    <div id="parent2"></div> 
    <button onclick="rem()">remove</button> 
    <button onclick="remChild()">removeChild</button> 
    <button onclick="ins()">insert</button> 
    </body> 
</html> 

在这里,我尝试删除 '孩子' 格在2种方式:

  1. 通过调用 '孩子' 的div

  2. '删除' 方法通过在'parent1'节点上调用'removeChild'方法

但是在这两种情况下,节点并未实际移除。我总是可以将'child'div插入'parent2'。

我可以理解,在第二种情况下,'孩子'从'parent1'没有绑定,并且没有被实际删除。但是在第一种情况下,这个'孩子'是不是永久删除?

尝试插入不存在的元素时,是否应该不会出现错误?

请解释。

而且如果元素确实存在,甚至称元素“删除”,后:

  1. 如何被“删除”从“removeChild之”有什么不同?正如我所看到的,这两种方法都是从父母手中解脱出来的,但元素仍然占据着记忆。

  2. 有什么方法可以确保元素实际上从内存中删除?

回答

3

节点实际上未被删除

的混乱可能是因为你可能会认为移除元素意味着像杀死或破坏它。

enter image description here

但事实上,removal概念基本上意味着打破一个小孩子与其父之间的关系。这只是一个分队。

enter image description here

我不应该得到而试图插入一个不存在的元素的错误?

不,因为它仍然存在。

removeremoveChild有什么不同?

remove只需要提及孩子。 removeChild需要父母和孩子的参考。结果是相同的。

有什么方法可以确保元素实际上从内存中删除?

不可以,你只能重新引用它,并希望有一个垃圾收集器,它会检测到对象没有被引用,然后将其删除。

0

remove是一个新功能。这是一种快捷方式,可以更简单地删除元素而无需查找父节点。很遗憾,在旧版本的Internet Explorer上不可用,因此,除非您不想支持此浏览器,否则您必须使用removeChild或使用polyfill

子元素保留在内存中的原因是您的代码保留对它的引用。

如果你

childDiv = null; 

那么就没有引用指向它,浏览器可以释放内存。

+0

我试着通过'removeChild'去除'child',并删除了对它的引用。这个时间元素也被永久删除。我无法得到'小孩'回来。所以'removeChild'不只是从父类中解除绑定元素,而是实际移除它?由于我在代码中保留了参考资料,我能够获得“孩子”吗?所以它只是保持引用计数:就像保持跟踪指向一个对象的指针数量?只要引用计数为0,内存就释放了? – Prasoon

+0

仅供参考,'删除'在IE 11上可用。 – Prasoon

+0

@Prasoon更全局的情况下,任何不可访问的值(使用引用或DOM函数)都可以由引擎释放(通常是)。 –

相关问题