當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


JQuery .detach()用法及代碼示例

用法
.detach(  [selector ] ) => jQuery

說明:從 DOM 中刪除匹配的元素集。

  • 添加的版本:1.4.detach( [selector ] )

    • selector
      類型:Selector
      篩選要刪除的匹配元素集的選擇器表達式。

.detach() 方法與 .remove() 相同,除了 .detach() 保留與已刪除元素關聯的所有 jQuery 數據。當移除的元素稍後要重新插入到 DOM 中時,此方法很有用。

例子:

從 DOM 中分離所有段落

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>detach demo</title>
  <style>
  p {
    background: yellow;
    margin: 6px 0;
  }
  p.off {
    background: black;
  }
  </style>
  <script src="https://code.jquery.com/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>

演示:

相關用法


注:本文由純淨天空篩選整理自jquery.com大神的英文原創作品 .detach()。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。