jQuery 插入insertAfter()與insertBefore()
與內(nèi)部插入處理一樣,jQuery由於內(nèi)容目標(biāo)的位置不同,然增加了2個(gè)新的方法insertAfter與insertBefore
before()和.insertBefore()實(shí)現(xiàn)相同的功能。主要的區(qū)別是語法——內(nèi)容和目標(biāo)的位置。 對(duì)於before()選擇表達(dá)式在函數(shù)前面,內(nèi)容作為參數(shù),而.insertBefore()剛好相反,內(nèi)容在方法前面,它將被放在參數(shù)裡元素的前面
after()和.insertAfter () 實(shí)現(xiàn)同樣的功能。主要的不同是語法——特別是(插入)內(nèi)容和目標(biāo)的位置。 對(duì)於after()選擇表達(dá)式在函數(shù)的前面,參數(shù)是將要插入的內(nèi)容。對(duì)於 .insertAfter(), 剛好相反,內(nèi)容在方法前面,它將被放在參數(shù)裡元素的後面
before、after與insertBefore。 insertAfter的除了目標(biāo)與位置的不同外,後面的不支援多參數(shù)處理
注意事項(xiàng):
insertAfter將JQuery封裝好的元素插入到指定元素的後面,如果元素後面有元素了,那將後面的元素後移,然後將JQuery物件插入;
insertBefore將JQuery封裝好的元素插入到指定元素的前面,如果元素前面有元素了,那將前面的元素前移,然後將JQuery物件插入;
#下面我們來寫一段程式碼:
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title></title> <script src="http://lib.sinaapp.com/js/jquery/1.9.1/jquery-1.9.1.min.js"></script> <style> .test1 { background: #bbffaa; } .test2 { background: yellow; } </style> </head> <body> <button id="bt1">insertBefore添加元素</button> <button id="bt2">insertAfter添加元素</button> <div class="aaron"> <p class="test1">php 中文網(wǎng)</p> </div> <div class="test2">php.cn</p> </div> <script type="text/javascript"> $("#bt1").on('click', function() { //在test1元素前后插入集合中每個(gè)匹配的元素 //不支持多參數(shù) $('<p style="color:red">測(cè)試insertBefore方法增加</p>', '<p style="color:red">多參數(shù)</p>').insertBefore($(".test1")) }) </script> <script type="text/javascript"> $("#bt2").on('click', function() { //在test2元素前后插入集合中每個(gè)匹配的元素 //不支持多參數(shù) $('<p style="color:red">測(cè)試insertAfter方法增加</p>', '<p style="color:red">多參數(shù)</p>').insertAfter($(".test2")) }) </script> </body> </html>
大家測(cè)試一下,看有什麼樣的差別