.detach()
返回: jQuery
.detach( [selector ] )
描述:从DOM中删除匹配的元素集合。
.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-1.10.2.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>
演示结果