.after()
.after( content ) 返回:jQuery
描述: 根據(jù)參數(shù)設(shè)定在每一個(gè)匹配的元素之后插入內(nèi)容。
-
version added: 1.0.after( content )
content一個(gè)元素,HTML字符串,或者jQuery對(duì)象,用來(lái)插在每個(gè)匹配元素的后面。
-
version added: 1.4.after( function(index) )
function(index)一個(gè)返回HTML字符串的函數(shù),這個(gè)字符串會(huì)被插入到每個(gè)匹配元素的后面。
.after()和.insertAfter()實(shí)現(xiàn)同樣的功能。主要的不同是語(yǔ)法——特別是內(nèi)容和目標(biāo)的位置。
對(duì)于 .after(), 選擇表達(dá)式在函數(shù)的前面,參數(shù)是將要插入的內(nèi)容。
對(duì)于.insertAfter(), 剛好相反,內(nèi)容在方法前面,它將被放在參數(shù)里元素的后面。
請(qǐng)看下面的HTM
<div class="container"> <h2>Greetings</h2> <div class="inner">Hello</div> <div class="inner">Goodbye</div> </div>
我們可以創(chuàng)建內(nèi)容然后同時(shí)插在好幾個(gè)元素后面:
$('.inner').after('<p>Test</p>');
新得到的內(nèi)容:
<div class="container"> <h2>Greetings</h2> <div class="inner">Hello</div> <p>Test</p> <div class="inner">Goodbye</div> <p>Test</p> </div>
我們也可以在頁(yè)面上選擇一個(gè)元素然后插在另一個(gè)元素后面:
$('.container').after($('h2'));
如果一個(gè)被選中的元素被插在另外一個(gè)地方,這是移動(dòng)而不是復(fù)制:
<div class="container"> <div class="inner">Hello</div> <div class="inner">Goodbye</div> </div> <h2>Greetings</h2>
如果有多個(gè)目標(biāo)元素,內(nèi)容將被復(fù)制然后被插入到每個(gè)目標(biāo)后面。
插入分離的DOM節(jié)點(diǎn)
對(duì)于jQuery 1.4, .before()和.after()同時(shí)也會(huì)對(duì)分離的DOM元素有效。例如,下面的代碼:
$('<div/>').after('<p></p>');
結(jié)果是一個(gè)包含一個(gè)div和一個(gè)段落的JQuery集合。因此,我們可以更進(jìn)一步操作這個(gè)集合,即使在將它插入document之前。
$('<div/>').after('<p></p>').addClass('foo')
.filter('p').attr('id', 'bar').html('hello')
.end()
.appendTo('body');
結(jié)果是下面的代碼被插到</body>標(biāo)簽之前:
<div class="foo"></div> <p class="foo" id="bar">hello</p>
對(duì)于jQuery 1.4, .after()允許我們傳入一個(gè)函數(shù),改函數(shù)返回要被插入的元素。
$('p').after(function() {
return '<div>' + this.className + '</div>';
});
上面的代碼在每個(gè)段落后插入一個(gè)<div>,<div>里面是該段落的class名稱(chēng)。
例子:
例如: 在所有的段落后插入一些HTML。
<!DOCTYPE html>
<html>
<head>
<style>p { background:yellow; }</style>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
</head>
<body>
<p>I would like to say: </p>
<script>$("p").after("<b>Hello</b>");</script>
</body>
</html>
Demo:
例如:在所有的段落后插入一個(gè)DOM元素。
<!DOCTYPE html>
<html>
<head>
<style>p { background:yellow; }</style>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
</head>
<body>
<p>I would like to say: </p>
<script>$("p").after( document.createTextNode("Hello") );</script>
</body>
</html>
Demo:
例如:在所有段落后插入一個(gè)jQuery對(duì)象。
<!DOCTYPE html>
<html>
<head>
<style>p { background:yellow; }</style>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
</head>
<body>
<b>Hello</b><p>I would like to say: </p>
<script>$("p").after( $("b") );</script>
</body>
</html>