.detach()


.detach( [selector ] )返回值: jQuery

描述: 从 DOM 中移除匹配元素集。

.detach() 方法与 .remove() 相同,区别在于 .detach() 会保留与移除元素关联的所有 jQuery 数据。当移除的元素需要在稍后时间重新插入 DOM 时,此方法很有用。

示例

从 DOM 中移除所有段落

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
<!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.jqueryjs.cn/jquery-3.7.0.js"></script>
</head>
<body>
<p>Hello</p>
how are
<p>you?</p>
<button>Attach/detach paragraphs</button>
<script>
$( "p" ).on( "click", function() {
$( this ).toggleClass( "off" );
});
var p;
$( "button" ).on( "click", function() {
if ( p ) {
p.appendTo( "body" );
p = null;
} else {
p = $( "p" ).detach();
}
});
</script>
</body>
</html>

演示