detach()

从DOM中去掉所有匹配的元素。

.detach ([ selector ])

selector 类型: Selector 。一个选择表达式将需要移除的元素从匹配的元素中过滤出来。

.detach() 方法和 .remove() 一样,除了 .detach() 保存所有jQuery数据和被移走的元素相关联。当需要移走一个元素,不久又将该元素插入DOM时,这种方法很有用。

例子

删除DOM中所有段落

<!DOCTYPE html>
<html>
<head>
  <style>p { background:yellow; margin:6px 0; } p.off { background: black; }</style>
  <script src="./static/js/jquery-3.5.0.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>

Hello

how are

you?

上篇: unwrap()

下篇: empty()