jQuery学习——DOM 移除与替代
.detach()
描述: 从DOM中去掉所有匹配的元素。
.detach() 方法和.remove()一样, 除了 .detach()保存所有jQuery数据和被移走的元素相关联。当需要移走一个元素,不久又将该元素插入DOM时,这种方法很有用。
删除DOM中所有段落
<!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>
使用.empty()如果<div>里面包含任何数量的嵌套元素,他们也会被移走。
为了避免内存泄漏,jQuery先移除子元素的数据和事件处理函数,然后移除子元素。
如果你想删除元素,不破坏他们的数据或事件处理程序(这些绑定的信息还可以在之后被重新添加回来),请使用.detach()代替 。
和 .empty()相似。.remove() 将元素移出DOM。 当我们想将元素自身移除时我们用 .remove(),同时也会移除元素内部的一切,包括绑定的事件及与该元素相关的jQuery数据。要删除的元素不删除数据和事件的情况下,使用.detach()来代替。
<div class="container"> <div class="hello">Hello</div> <div class="goodbye">Goodbye</div> </div>
$('.hello').remove();
<div class="container"> <div class="goodbye">Goodbye</div> </div>
.unwarp()将匹配元素集合的父级元素删除,保留自身(和兄弟元素,如果存在)在原来的位置。不接受参数
.warp()相反,加上元素
.replaceAll() 描述: 用集合的匹配元素替换每个目标元素。
<div class="container"> <div class="inner first">Hello</div> <div class="inner second">And</div> <div class="inner third">Goodbye</div> </div>
$('<h2>New heading</h2>').replaceAll('.inner');
<div class="container"> <h2>New heading</h2> <h2>New heading</h2> <h2>New heading</h2> </div>
$('.first').replaceAll('.third');
<div class="container"> <div class="inner second">And</div> <div class="inner first">Hello</div> </div>
.replaceWith()与.replaceAll()相反。
并且支持方法
$("button").click(function () { $(this).replaceWith( "<div>" + $(this).text() + "</div>" ); });

浙公网安备 33010602011771号