jQuery DOM操作replaceWith()和replaceAll()
之前學(xué)習(xí)了節(jié)點的內(nèi)插入、外插入以及刪除方法,這節(jié)會學(xué)習(xí)替換方法replaceWith
.replaceWith( newContent ):用提供的內(nèi)容替換集合中所有匹配的元素並且返回被刪除元素的集合
簡單來說:用$()選擇節(jié)點A,呼叫replaceWith方法,傳入一個新的內(nèi)容B(HTML字串,DOM元素,或jQuery物件)用來取代選取的節(jié)點A
看個簡單的範(fàn)例:一段HTML程式碼
<div>
? ?<p>第一段</p>
? ?<p>第一段</p>
? ?<p>第二段</p>
? ?<p>第三段</p>
</div>
##取代第二段的節(jié)點與內(nèi)容
#$("p:eq(1)").replaceWith('<a style="color:red">取代第二段的內(nèi)容</a>')
#透過jQuery篩選出第二個p元素,呼叫replaceWith進(jìn)行替換,結(jié)果如下
##<div> ? ?<p>第一段</p>
? ?<p>第一段</p>
? ?<a style ="color:red">取代第二段的內(nèi)容</a>'
? ?<p>第三段</p>
</div>
#.replaceAll( target ) :用集合的匹配元素取代每個目標(biāo)元素
.replaceAll()和.replaceWith()功能類似,但是目標(biāo)和來源相反,用上述的HTML結(jié)構(gòu),我們用replaceAll處理
$('<a style="color:red">取代第二段的內(nèi)容</a>').replaceAll('p:eq( 1)')
總結(jié):
????replaceAll()和.replaceWith()功能類似,主要為目標(biāo)和來源的位置差異
????replaceWith()與.replaceAll() 方法會刪除所有與節(jié)點相關(guān)聯(lián)的資料和事件處理程序
????replaceWith()方法,且與大部分其他jQuery方法一樣,傳回jQuery對象,所以可以和其他方法連結(jié)使用
????replaceWith()方法回傳的jQuery物件所引用的是替換前的節(jié)點,而不是透過replaceWith/replaceAll方法取代後的節(jié)點
看下面的實例:
<!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替換內(nèi)容</button> <button class="bt2">點擊,通過rreplaceAll替換內(nèi)容</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"> //只克隆節(jié)點 //不克隆事件 $(".bt1").click(function(){ //找到內(nèi)容為第二段的p元素 //通過replaceWith刪除并替換這個節(jié)點 $(".right > div:first p:eq(1)").replaceWith('<a style="color:red">replaceWith替換第二段的內(nèi)容</a>') }) </script> <script type="text/javascript"> //找到內(nèi)容為第六段的p元素 //通過replaceAll刪除并替換這個節(jié)點 $(".bt2").click(function() { $('<a style="color:red">replaceAll替換第六段的內(nèi)容</a>').replaceAll('.right > div:last p:last'); }) </script> </body> </html>