本節說一下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 = https://www.cnblogs.com/greatdesert/p/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
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/31427.html
標籤:jQuery
上一篇:js獲取串列多條資料(介面)
