DOM替换replaceWith()和replaceAll()

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方法替换后的节点

<script type="text/javascript">
//只克隆节点
//不克隆事件
$(".bt1").click(function(){
$('.right > div:first p:eq(1)').replaceWith("<p style='color','red'>jhaj</p>")
})
</script>
<script type="text/javascript">
//找到内容为第六段的p元素
//通过replaceAll删除并替换这个节点
$(".bt2").click(function(){
$("<p style='color','pink'>hahha</p>").replaceAll(".right div:last p:first")
})
</script>

原文地址:https://www.cnblogs.com/liaolijun/p/7325168.html