Jquery教程
Jquery动效
Jquery HTML/CSS
Jquery 事件
jquery常用

jQuery detach()

jQuery detach()方法用于删除选定的元素,包括所有文本和子节点,并且仅保留数据和事件。
此方法将保存已删除元素的副本,以便以后在需要时重新插入。
还有一些其他方法也可用于删除元素,例如jQuery remove()方法,jQuery empty()方法等。但是它们之间有一些区别。
jQuery remove()方法:该方法用于删除元素
jQuery empty()方法:该方法用于仅删除所选元素中的内容。
语法:
$(selector).detach()

jQuery detach()方法的示例

让我们以一个示例来演示jQuery detach()方法的效果。
<!DOCTYPE html>
<html>
<head>
<script src="/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
  $("button").click(function(){
    $("p").detach();
  });
});
</script>
</head>
<body>
<p>Hello Guys!</p>
<p>This is lidihuo.com</p>
<button>Click here to detach all p elements</button>
</body>
</html>
输出:

Hello Guys!

This is lidihuo.com

jQuery detach()示例2

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>detach demo</title>
  <style>
  p {
    background: lightpink;
    margin: 6px 0;
  }
  </style>
  <script src="/jquery-1.10.2.js"></script>
</head>
<body>
<p>Hello Guys!</p>
<p>This is lidihuo.com</p>
<button>Click here to Attach/detach all p elements. </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 Guys!

This is lidihuo.com

detach()和remove()方法之间的差异

让我们以一个示例来清除detach()和remove()方法之间的区别:

jQuery detach()示例3

<!DOCTYPE html>
<html>
<head>
<script src="/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("#btn1").click(function(){
        $("body").append($("#p1").detach());
    });
    $("#btn2").click(function(){
        $("body").append($("#p2").remove());
    });
    $("p").click(function(){
        $(this).animate({fontSize: "+=1px"})
    });
});
</script>
</head>
<body>
<p id="p1"><b>This paragraph will keep its click event even after it is moved.</b></p>
<p id="p2">This paragraph will not keep its click event after it is moved.</p>
<button id="btn1">Detach and append p element</button>
<button id="btn2">Remove and append p element</button>
</body>
</html>

This paragraph will keep its click event even after it is moved.

This paragraph will not keep its click event after it is moved.

注意:通过以上示例,很明显jQuery detach()方法不会删除内部数据和事件。在上面的示例中,即使应用了detach()方法,click事件仍然保持安全。
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4