The difference between jQuery DOM operations detach() and remove()
JQuery is a very powerful tool library. In work development, some methods are ignored by us because they are not commonly used or have not been noticed.
remove() and detach() may be one of them. Maybe we use remove() more, but detach() may be less used.
Through a comparison table To explain the difference between the two methods
remove: remove node
No parameters, remove the entire node itself and all the internal components of the node Node, including events and data on the node
With parameters, remove the filtered node and all nodes inside the node, including events and data on the node
detach: remove node
The processing of removal is consistent with remove
Different from remove(), all bound events, additional data, etc. will be retained
For example: $(" p").detach() will remove the object, but the display effect will be gone. But it still exists in memory. When you append, you return to the document flow. It showed up again.
Let’s analyze it in detail through examples:
<html> <head> <meta http-equiv="Content-type" content="text/html; charset=utf-8" /> <style type="text/css"> p{ border: 1px solid red; } </style> <script src="http://libs.baidu.com/jquery/1.9.1/jquery.js"></script> </head> <body> <p>元素p1,同時(shí)綁定點(diǎn)擊事件</p> <p>元素p2,同時(shí)綁定點(diǎn)擊事件</p> <h3>通過(guò)點(diǎn)擊2個(gè)按鈕后觀察方法處理的區(qū)別</h3> <button>點(diǎn)擊通過(guò)remove處理元素p1</button> <button>點(diǎn)擊通過(guò)detach處理元素p2</button> </body> <script type="text/javascript"> //給頁(yè)面上2個(gè)p元素都綁定時(shí)間 $('p').click(function(e) { alert(e.target.innerHTML) }) $("button:first").click(function() { var p = $("p:first").remove(); p.css('color','red').text('p1通過(guò)remove處理后,點(diǎn)擊該元素,事件丟失') $("body").append(p); }); $("button:last").click(function() { var p = $("p:first").detach(); p.css('color','blue').text('p2通過(guò)detach處理后,點(diǎn)擊該元素事件存在') $("body").append(p); }); </script> </script> </html>