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,同时绑定点击事件</p> <p>元素p2,同时绑定点击事件</p> <h3>通过点击2个按钮后观察方法处理的区别</h3> <button>点击通过remove处理元素p1</button> <button>点击通过detach处理元素p2</button> </body> <script type="text/javascript"> //给页面上2个p元素都绑定时间 $('p').click(function(e) { alert(e.target.innerHTML) }) $("button:first").click(function() { var p = $("p:first").remove(); p.css('color','red').text('p1通过remove处理后,点击该元素,事件丢失') $("body").append(p); }); $("button:last").click(function() { var p = $("p:first").detach(); p.css('color','blue').text('p2通过detach处理后,点击该元素事件存在') $("body").append(p); }); </script> </script> </html>