jQuery DOM操作replaceWith()和replaceAll()
之前學(xué)習(xí)了節(jié)點(diǎn)的內(nèi)插入、外插入以及刪除方法,這節(jié)會(huì)學(xué)習(xí)替換方法replaceWith
.replaceWith( newContent ):用提供的內(nèi)容替換集合中所有匹配的元素并且返回被刪除元素的集合
簡(jiǎn)單來(lái)說(shuō):用$()選擇節(jié)點(diǎn)A,調(diào)用replaceWith方法,傳入一個(gè)新的內(nèi)容B(HTML字符串,DOM元素,或者jQuery對(duì)象)用來(lái)替換選中的節(jié)點(diǎn)A
看個(gè)簡(jiǎn)單的例子:一段HTML代碼
<div>
? ?<p>第一段</p>
? ?<p>第二段</p>
? ?<p>第三段</p>
</div>
替換第二段的節(jié)點(diǎn)與內(nèi)容
$("p:eq(1)").replaceWith('<a style="color:red">替換第二段的內(nèi)容</a>')
通過(guò)jQuery篩選出第二個(gè)p元素,調(diào)用replaceWith進(jìn)行替換,結(jié)果如下
<div>
? ?<p>第一段</p>
? ?<a style="color:red">替換第二段的內(nèi)容</a>'
? ?<p>第三段</p>
</div>
.replaceAll( target ) :用集合的匹配元素替換每個(gè)目標(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)和源的位置區(qū)別
????replaceWith()與.replaceAll() 方法會(huì)刪除與節(jié)點(diǎn)相關(guān)聯(lián)的所有數(shù)據(jù)和事件處理程序
????replaceWith()方法,和大部分其他jQuery方法一樣,返回jQuery對(duì)象,所以可以和其他方法鏈接使用
????replaceWith()方法返回的jQuery對(duì)象引用的是替換前的節(jié)點(diǎn),而不是通過(guò)replaceWith/replaceAll方法替換后的節(jié)點(diǎn)
看下面的實(shí)例:
<!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">點(diǎn)擊,通過(guò)replaceWith替換內(nèi)容</button> <button class="bt2">點(diǎn)擊,通過(guò)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é)點(diǎn) //不克隆事件 $(".bt1").click(function(){ //找到內(nèi)容為第二段的p元素 //通過(guò)replaceWith刪除并替換這個(gè)節(jié)點(diǎn) $(".right > div:first p:eq(1)").replaceWith('<a style="color:red">replaceWith替換第二段的內(nèi)容</a>') }) </script> <script type="text/javascript"> //找到內(nèi)容為第六段的p元素 //通過(guò)replaceAll刪除并替換這個(gè)節(jié)點(diǎn) $(".bt2").click(function() { $('<a style="color:red">replaceAll替換第六段的內(nèi)容</a>').replaceAll('.right > div:last p:last'); }) </script> </body> </html>