返回值:jQuerydetach([selector])

从 DOM 中移除匹配的元素,但保留移除元素上的事件及 jQuery 数据。

.detach() 方法和 .remove() 一样,只是 .detach() 会保留所有被移除元素上的事件及 jQuery 数据。这个方法特别适用于需要将之前移除的元素重新插入到 DOM 中的情况。

示例:

从 DOM 中移除所有的段落。

<!DOCTYPE html>
<html>
<head>
<style>p { background:yellow; margin:6px 0; } p.off { background: black; }</style>
<script src="jquery.min.js"></script>
</head>
<body>

<p>Hello</p> 
  how are 
  <p>you?</p>
  <button>Attach/detach paragraphs</button>

<script>


    $("p").click(function(){
      $(this).toggleClass("off");
    });
    var p;
    $("button").click(function(){
      if ( p ) {
        p.appendTo("body");
        p = null;
      } else {
        p = $("p").detach();
      }
    });

</script>
</body>
</html>

演示: