jQuery 源码解析(二十三) DOM操作模块 替换元素 详解
- 作者: 别动v我有枪
- 来源: 51数据库
- 2021-08-04
本节说一下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://www.51sjk.com/Upload/Articles/1/0/267/267585_20210708020313144.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
推荐阅读
