The difference between detach of and remove of in jquery

  • 2021-07-24 10:06:21
  • OfStack

JQuery is a very strong tool library, in the development of work, but some of the methods are still not commonly used, or not noticed by us and ignored.

remove () and detach () may be one of them. Maybe we use remove () more and detach () less

Explain the differences between the two methods through a comparison table

方法名

参数

事件及数据是否也被移除

元素自身是否被移除

remove

支持选择器表达

是(无参数时),有参数时要根据参数所涉及的范围

detach

参数同remove

情况同remove

remove: Remove Node

-No parameters, remove the entire node of itself and all nodes within the 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

-Remove treatment with remove1

-Unlike remove (), all bound events, additional data, and so on are preserved

-For example: $("p"). detach () removes the object, but the display is gone. But it still exists in memory. After you append, you are back in the document flow. It shows up again.

eq:


<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>
<h3> To the page 2 A p Element node binding click event , Click to pop up your own node content </h3>

<p> Element p1 While binding click-on events </p>

<p> Element p2 While binding click-on events </p>

<h3> By clicking 2 The difference of observation method processing after 10 buttons </h3>
<button> Click through remove Processing element p1</button>
<button> Click through detach Processing element p2</button>
</body>
<script type="text/javascript">
  // To the page 2 A p Elements are bound to time  
  $('p').click(function (e) {
    alert(e.target.innerHTML)
  })

  $("button:first").click(function () {
    var p = $("p:first").remove();
    p.css('color', 'red').html('p1 Pass remove After treatment , Click on the element , Event loss ')
    $("body").append(p);
  });

  $("button:last").click(function () {
    var p = $("p:first").detach();
    p.css('color', 'blue').text('p2 Pass detach After treatment , Clicking on this element event exists ')
    $("body").append(p);
  });
</script>
</script>

</html >

Related articles: