Jquery empty() remove() detach() 方法的區別

來源:互聯網
上載者:User

 引言:
最近項目中用到了這幾個方法,感覺很大程度上有些相似,查了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之後是有效。


綜上所述,可以得到這個三個方法的上述比較表格了。

聯繫我們

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