Jquery empty() remove() detach() 方法的区别

来源:岁月联盟 编辑:exp 时间:2012-09-19

 引言:
最近项目中用到了这几个方法,感觉很大程度上有些相似,查了Jquery的api,同时也找了很多博客文章,发现还是理解不到区别。最后在很多材料和自己的事例验证中,终于找到了区别,不敢独占特拿出来分享。

 


方法简介:

 empty()
This method removes not only child (and other descendant) elements, but also any text within the set of matched elements. This is because, according to the DOM specification, any string of text within an element is considered a child node of that element.
该方法不仅删除它的子节点,同时也删除该节点的文本域(根据DOM规范,节点的文本域也被认为是子节点)。

 

 remove( [selector] )
selectorA selector expression that filters the set of matched elements to be removed.

Similar to .empty(), the .remove() method takes elements out of the DOM. Use.remove() when you want to remove the element itself, as well as everything inside it. In addition to the elements themselves, all bound events and jQuery data associated with the elements are removed. To remove the elements without removing data and events, use.detach() instead.
和empty方法类似,remove方法也是从DOM里删除元素。当你想要删除节点本身和节点里的所有东西的时候,可以使用remove方法。除了节点本身以外,节点绑定的事件 和该节点相关的JQuery数据,也会被同时清除。当需要清除节点本身,但是不需要清除绑定的事件和数据的时候,可以使用detach方法。


 detach( [selector] )
selectorA selector expression that filters the set of matched elements to be removed.

The .detach() method is the same as .remove(), except that .detach() keeps all jQuery data associated with the removed elements. This method is useful when removed elements are to be reinserted into the DOM at a later time.
detach方法和remove方法很相似,但是它会保留所有JQuery相关的数据和绑定的事件。当你删除之后,想要在后来的某个时候重新加入时,这个方法将会很有用。
 

 

三者区别:
empty,remove,detach方法的区别

方法名称

元素本身(包含所有属性)

绑定事件和JQuery相关数据

文本域及子节点

empty()
不删除

不删除

删除

remove()
删除

删除

删除

detach()
删除

不删除

删除

 

 

示例验证:
验证环境: JQuery-1.8.0.min.js, Firefox 11.0, Firebug1.9.2;

1、验证是否删除元素本书(包含所有属性)、文本域及子节点
代码如下:

[html]
 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 
<html> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 
<title>Test Jquery remove detach empty</title> 
<style>p { background:yellow; margin:6px 0; } p.off { background: black; }</style> 
<script src="js/jquery-1.8.0.min.js"></script> 
<script> 
    $(document).ready(function(){ 
        $("p").click(function(){ 
            $(this).toggleClass("off"); 
        }); 
         
        var p; 
        $("#button").click(function(){ 
              if ( p ) { 
                p.appendTo("body"); 
                p = null; 
              } else { 
                p = $("p").detach(); 
            // p = $("p").remove(); 
            // p = $("p").empty(); 
              }  
        }); 
    });  
</script> 
</head> 
 
<body> 
  <p id="A">Hello <span>subNode</span></p> 
  how are 
  <p id="B">you? <span>subNode</span></p> 
   
  <input type="button" id="button" value="Attach/detach paragraphs" />  
 
</body> 
</html> 
detach() 方法:
执行之前的HTML DOM结构如图:

 

执行删除之后的 HTML DOM结构如图:

 

观察可知使用detach方法,删掉了元素<p>本身即它的所有属性(id 等), 文本域及其子节点<span>subNode</span>.

其他方法,类似可以验证,这里就不赘述。


2、验证绑定的事件和JQuery相关数据
这里需要说明的是: 绑定事件,指的是JQuery动态绑定的事件,不是通过元素的属性指定的事件。(下面会举例说明)

JQuery 相关数据,不太懂指的什么,没有找到相关示例,希望有识之士不吝赐教。


下面的示例仅针对绑定事件,便于大家理解:

[html] 
 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 
<html> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 
<title>Test Jquery remove detach empty</title> 
<style> 
p {  
    background:yellow;  
    margin:6px 0; 
}  
p.off {  
    background: black;  

</style> 
<script src="js/jquery-1.8.0.min.js"></script> 
<script> 
    $(document).ready(function(){ 
         
        // JQuery 为P标签动态绑定click事件 
        $("p").click(function(){ 
            $(this).toggleClass("off"); 
        }); 
         
        var p; 
        $("#button").click(function(){ 
              if ( p ) { 
                p.appendTo("body"); 
                p = null; 
              } else { 
                p = $("p").detach(); 
            // p = $("p").remove(); 
            // p = $("p").empty(); 
              }  
        }); 
    });  
</script> 
</head> 
 
<body> 
  <p id="A">Hello <span>subNode</span></p> 
  how are 
  <p id="B">you? <span>subNode</span></p> 
   
  <input type="button" id="button" value="Attach/detach paragraphs" />  
 
</body> 
</html> 
运行该页面,点击按钮,删除;  再次点击按钮,删除的<p>标签,重新加入到body的底部,这里我们重点验证的是,重新加入后的绑定事件click是否有效【这里的click事件为,点击P标签,class在黄色和黑色之间切换】。
 

1)  验证detach方法


可以看到执行detach方法,重新添加之后,JQuery动态绑定的click事件,toggleClass生效,说明之前删除的时候没有把动态绑定的事件删除。

 


2)  验证remove方法
修改程序中以下部分:

[javascript]
// p = $("p").detach(); 
p = $("p").remove(); 
测试remove函数,同样是先删除在加入,执行完后的效果:


可以发现调用remove方法之后,再重新把删除的标签加入到body后时,发现JQuery动态绑定的事件,已经失效,点击P标签,class不能切换。说明在执行remove的时候,已经把JQuery动态绑定的事件删除了。

 


3)  验证empty方法:
要验证empty方法,要麻烦一点,在删除之后,重新加入之后,text为空,不能够点击测试click事件,因此我们需要新增一个按钮,为这种情况增加text,便于测试click事件。

代码如下:

[html]
 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 
<html> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 
<title>Test Jquery remove detach empty</title> 
<style> 
p {  
    background:yellow;  
    margin:6px 0; 
}  
p.off {  
    background: black;  

</style> 
<script src="js/jquery-1.8.0.min.js"></script> 
<script> 
    $(document).ready(function(){ 
         
        // JQuery 为P标签动态绑定click事件 
        $("p").click(function(){ 
            $(this).toggleClass("off"); 
        }); 
         
        var p; 
        $("#button").click(function(){ 
              if ( p ) { 
                p.appendTo("body"); 
                p = null; 
              } else { 
                // p = $("p").detach(); 
                // p = $("p").remove(); 
                p = $("p").empty(); 
              }  
        }); 
         
        // 为删除之后重新加入的p标签加入text 
        $("#buttonA").click(function(){ 
            $("#A").text("Hello"); 
            $("#B").text("you?"); 
        }); 
    });  
</script> 
</head> 
 
<body> 
  <p id="A">Hello <span>subNode</span></p> 
  how are 
  <p id="B">you? <span>subNode</span></p> 
   
  <input type="button" id="button" value="Attach/detach paragraphs" /> <br/> 
  <input type="button" id="buttonA" value="addTextA" /> <br/> 
 
</body> 
</html> 
执行效果如图:

 

可以发现empty方法,没有删除动态绑定事件。


4)  补充讲解:
为了更好的理解这里所说的绑定事件是JQuery的动态绑定事件,我们修改一下程序,使用onclick属性,把click事件作为一个属性值,来静态绑定。

修改后的程序如下:

[html] 
 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 
<html> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 
<title>Test Jquery remove detach empty</title> 
<style> 
p {  
    background:yellow;  
    margin:6px 0; 
}  www.2cto.com
p.off {  
    background: black;  

</style> 
<script src="js/jquery-1.8.0.min.js"></script> 
<script> 
    // 处理P标签click事件 
    function clickHandler(element){ 
        $(element).toggleClass("off"); 
    } 
 
    $(document).ready(function(){        
        var p; 
        $("#button").click(function(){ 
              if ( p ) { 
                p.appendTo("body"); 
                p = null; 
              } else { 
                // p = $("p").detach(); 
                 p = $("p").remove(); 
                // p = $("p").empty(); 
              }  
        });  
         
    });  
</script> 
</head> 
 
<body> 
  <p id="A" onclick="clickHandler(this)">Hello <span>subNode</span></p> 
  how are 
  <p id="B" onclick="clickHandler(this)">you? <span>subNode</span></p> 
   
  <input type="button" id="button" value="Attach/detach paragraphs" /> <br/> 
 
</body> 
</html> 

我们再次使用remove方法,删除然后在append,发现事件响应有效了。其实这里的click事件已经作为一个静态的p元素的一个属性onclick的值了。所有append之后是有效的。


综上所述,可以得到这个三个方法的上述比较表格了。