.detach()


.detach( [selector ] )返回: jQuery

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

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

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

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

Demo: