DOM替换replaceWith()和replaceAll()
之前学习了节点的内插入、外插入以及删除方法,这节会学习替换方法replaceWith
.replaceWith( newContent ):用提供的内容替换集合中所有匹配的元素并且返回被删除元素的集合
简单来说:用$()选择节点A,调用replaceWith方法,传入一个新的内容B(HTML字符串,DOM元素,或者jQuery对象)用来替换选中的节点A
看个简单的例子:一段HTML代码
<div> <p>第一段</p> <p>第二段</p> <p>第三段</p> </div>
替换第二段的节点与内容
$("p:eq(1)").replaceWith('<a style="color:red">替换第二段的内容</a>')
通过jQuery筛选出第二个p元素,调用replaceWith进行替换,结果如下
<div> <p>第一段</p> <a style="color:red">替换第二段的内容</a>' <p>第三段</p> </div>
.replaceAll( target ) :用集合的匹配元素替换每个目标元素
.replaceAll()和.replaceWith()功能类似,但是目标和源相反,用上述的HTML结构,我们用replaceAll处理
$('<a style="color:red">替换第二段的内容</a>').replaceAll('p:eq(1)')
总结:
- .replaceAll()和.replaceWith()功能类似,主要是目标和源的位置区别
- .replaceWith()与.replaceAll() 方法会删除与节点相关联的所有数据和事件处理程序
- .replaceWith()方法,和大部分其他jQuery方法一样,返回jQuery对象,所以可以和其他方法链接使用
- .replaceWith()方法返回的jQuery对象引用的是替换前的节点,而不是通过replaceWith/replaceAll方法替换后的节点
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<title></title>
<script src="http://libs.baidu.com/jquery/1.9.1/jquery.js"></script>
<style>
.right div {
background: yellow;
}
</style>
</head>
<body>
<h2>replaceWith()和replaceAll()</h2>
<div class="left">
<button class="bt1">点击,通过replaceWith替换内容</button>
<button class="bt2">点击,通过rreplaceAll替换内容</button>
</div>
<div class="right">
<div>
<p>第一段</p>
<p>第二段</p>
<p>第三段</p>
</div>
<div>
<p>第四段</p>
<p>第五段</p>
<p>第六段</p>
</div>
</div>
<script type="text/javascript">
//只克隆节点
//不克隆事件
$(".bt1").on('click', function() {
//找到内容为第二段的p元素
//通过replaceWith删除并替换这个节点
$(".right > div:first p:eq(1)").replaceWith('<a style="color:red">replaceWith替换第二段的内容</a>')
})
</script>
<script type="text/javascript">
//找到内容为第六段的p元素
//通过replaceAll删除并替换这个节点
$(".bt2").on('click', function() {
$('<a style="color:red">replaceAll替换第六段的内容</a>').replaceAll('.right > div:last p:last');
})
</script>
</body>
</html>