DOM外部插入after()與before()
節點與節點之前有各種關係,除了父子,祖輩關係,還可以是兄弟關係。之前我們在處理節點插入的時候,接觸到了內部插入的幾個方法,這節我們開始講外部插入的處理,也就是兄弟之間的關係處理,這裏jQuery引入了2個方法,可以用來在匹配I的元素前後插入內容
選擇器的描述:
- before與after都是用來對相對選中元素外部增加相鄰的兄弟節點
- 2個方法都是都可以接收HTML字符串,DOM 元素,元素數組,或者jQuery對象,用來插入到集合中每個匹配元素的前面或者後面
- 2個方法都支持多個參數傳遞after(div1,div2,....) 可以參考右邊案例代碼
注意點:
- after向元素的後邊添加html代碼,如果元素後面有元素了,那將後面的元素後移,然後將html代碼插入
- before向元素的前邊添加html代碼,如果元素前面有元素了,那將前面的元素前移,然後將html代碼插
- <!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>
.aaron{
border: 1px solid red;
}
</style>
</head>
<body>
<h2>通過before與after添加元素</h2>
<button id="bt1">點擊通過jQuery的before添加元素</button>
<button id="bt2">點擊通過jQuery的after添加元素</button>
<div class="aaron">
<p class="test1">測試before</p>
</div>
<div class="aaron">
<p class="test2">測試after</p>
</div>
<script type="text/javascript">
$("#bt1").on('click', function() {
//在匹配test1元素集合中的每個元素前面插入p元素
$(".test1").before('<p style="color:red">before,在匹配元素之前增加</p>', '<p style="color:red">多參數</p>')
})
</script>
<script type="text/javascript">
$("#bt2").on('click', function() {
//在匹配test1元素集合中的每個元素後面插入p元素
$(".test2").after('<p style="color:blue">after,在匹配元素之後增加</p>', '<p style="color:blue">多參數</p>')
})
</script>
</body>