DOM外部插入insertAfter()與insertBefore()
與內(nèi)部插入處理一樣,jQuery由于內(nèi)容目標(biāo)的位置不同,然增加了2個新的方法insertAfter與insertBefore

- .before()和.insertBefore()實(shí)現(xiàn)同樣的功能。主要的區(qū)別是語法——內(nèi)容和目標(biāo)的位置。 對于before()選擇表達(dá)式在函數(shù)前面,內(nèi)容作為參數(shù),而.insertBefore()剛好相反,內(nèi)容在方法前面,它將被放在參數(shù)里元素的前面
- .after()和.insertAfter() 實(shí)現(xiàn)同樣的功能。主要的不同是語法——特別是(插入)內(nèi)容和目標(biāo)的位置。 對于after()選擇表達(dá)式在函數(shù)的前面,參數(shù)是將要插入的內(nèi)容。對于 .insertAfter(), 剛好相反,內(nèi)容在方法前面,它將被放在參數(shù)里元素的后面
- before、after與insertBefore。insertAfter的除了目標(biāo)與位置的不同外,后面的不支持多參數(shù)處理
注意事項(xiàng):
- insertAfter將JQuery封裝好的元素插入到指定元素的后面,如果元素后面有元素了,那將后面的元素后移,然后將JQuery對象插入;
- insertBefore將JQuery封裝好的元素插入到指定元素的前面,如果元素前面有元素了,那將前面的元素前移,然后將JQuery對象插入;
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<title></title>
<script src="http://idcbgp.cn/static/lib/jquery/1.9.1/jquery.js"></script>
<style>
.test1 {
background: #bbffaa;
}
.test2 {
background: yellow;
}
</style>
</head>
<body>
<h2>通過insertBefore與insertAfter添加元素</h2>
<button id="bt1">點(diǎn)擊通過jQuery的insertBefore添加元素</button>
<button id="bt2">點(diǎn)擊通過jQuery的insertAfter添加元素</button>
<div class="aaron">
<p class="test1">測試insertBefore,不支持多參數(shù)</p>
</div>
<div class="aaron">
<p class="test2">測試insertAfter,不支持多參數(shù)</p>
</div>
<script type="text/javascript">
$("#bt1").on('click', function() {
//在test1元素前后插入集合中每個匹配的元素
//不支持多參數(shù)
$('<p style="color:red">測試insertBefore方法增加</p>', '<p style="color:red">多參數(shù)</p>').insertBefore($(".test1"))
})
</script>
<script type="text/javascript">
$("#bt2").on('click', function() {
//在test2元素前后插入集合中每個匹配的元素
//不支持多參數(shù)
$('<p style="color:red">測試insertAfter方法增加</p>', '<p style="color:red">多參數(shù)</p>').insertAfter($(".test2"))
})
</script>
</body>
</html>
請驗(yàn)證,完成請求
由于請求次數(shù)過多,請先驗(yàn)證,完成再次請求