本节说一下DOM操作模块里的替换元素模块,该模块可将当前匹配的元素替换指定的DOM元素,有两个方法,如下:
- replaceWith(value) ;使用提供的新内容来替换匹配元素集合中的每个元素。value是新内容,可以是html字符串、DOM元素、jQuery对象或返回新内容的函数。
- replaceAll(value) ;使用匹配元素集合中的元素替换目标元素。内部执行.replaceWith(value)方法,只是语法顺序上不同。类似于append()和appendTo()。
举个栗子:
writer by:大沙漠 QQ:22969969
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <title>Document</title>
- <script src="http://libs.baidu.com/jquery/1.7.1/jquery.min.js"></script>
- </head>
- <body>
- <div id="test"><i>Hello World!</i></div>
- <button id="b1">测试1</button>
- <button id="b2">测试2</button>
- <script>
- b1.onclick=function(){ //修改#test的内容,用replaceWith()方法
- $('#test').replaceWith('<h1 id="test">Hello jQuery!</h1>')
- }
- b2.onclick=function(){ //修改#test的内容,用replaceAll()方法
- $('<p id="test">jQuery is Good!</p>').replaceAll('#test')
- }
- </script>
- </body>
- </html>
渲染如下:

当点击测试1按钮时,页面渲染如下:

当点击测试2按钮时,页面变为如下:

源码分析
replaceWith()的实现比较简单,代码如下:
- jQuery.fn.extend({
- replaceWith: function( value ) { //使用提供的新内容来替换匹配元素集合中的每个元素。value是新内容,可以是html字符串、DOM元素、jQuery对象或返回新内容的函数。
- if ( this[0] && this[0].parentNode ) { //如果至少有一个匹配元素,且该元素有父元素
- // Make sure that the elements are removed from the DOM before they are inserted
- // this can help fix replacing a parent with child elements
- if ( jQuery.isFunction( value ) ) { //如果value是函数
- return this.each(function(i) { //遍历匹配元素集合
- var self = jQuery(this), old = self.html();
- self.replaceWith( value.call( this, i, old ) ); //给每个元素调用value函数,并用该函数的返回值迭代调用replaceWith()函数。
- });
- }
- if ( typeof value !== "string" ) { //如果参数value不是字符串,则可能是DOM元素或jQuery对象
- value = jQuery( value ).detach(); //先用value创建一个jQuery对象,再调用.detach()把参数从value文档中删除,保留关联的数据和事件。
- }
- return this.each(function() { //遍历当前匹配元素
- var next = this.nextSibling, //下一个元素节点引用
- parent = this.parentNode; //上一个元素节点引用
- jQuery( this ).remove(); //调用.remove()移除后代元素和当前元素关联的数据和事件,以避免内存泄漏。
-
- if ( next ) { //如果有下一个元素
- jQuery(next).before( value ); //则调用$.fn.before()函数将新内容插入下一个兄弟元素之前;
- } else {
- jQuery(parent).append( value ); //否则调用$.fn.append()函数则将新内容插入父元素末尾。
- }
- });
- } else {
- return this.length ?
- this.pushStack( jQuery(jQuery.isFunction(value) ? value() : value), "replaceWith", value ) :
- this;
- }
- },
- })
比较简单,就是先调用remove()移除当前之前,然后调用前一个节点的before()或父节点的append()方法插入新的节点即可,对于replaceAll()来说,它和插入元素那几个方法一样,是replaceWith()的另一个写法,可以看这个链接:https://www.cnblogs.com/greatdesert/p/11732436.html