返回值:jQuerydetach([selector])
Remove the set of matched elements from the DOM.
-
1.4 新增detach([selector])
selector (Selector) 可选参数,A selector expression that filters the set of matched elements to be removed.
The .detach()
method is the same as .remove()
, except that .detach()
keeps all jQuery data associated with the removed elements. This method is useful when removed elements are to be reinserted
into the DOM at a later time.
示例:
Detach all paragraphs from the DOM
<!DOCTYPE html>
<html>
<head>
<style>p { background:yellow; margin:6px 0; } p.off { background: black; }</style>
<script src="jquery.min.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>