.after()
.after( content ) 返回:jQuery
描述: 根據(jù)參數(shù)設(shè)定在每一個匹配的元素之后插入內(nèi)容。
-
version added: 1.0.after( content )
content一個元素,HTML字符串,或者jQuery對象,用來插在每個匹配元素的后面。
-
version added: 1.4.after( function(index) )
function(index)一個返回HTML字符串的函數(shù),這個字符串會被插入到每個匹配元素的后面。
.after()和.insertAfter()實(shí)現(xiàn)同樣的功能。主要的不同是語法——特別是內(nèi)容和目標(biāo)的位置。
對于 .after(), 選擇表達(dá)式在函數(shù)的前面,參數(shù)是將要插入的內(nèi)容。
對于.insertAfter(), 剛好相反,內(nèi)容在方法前面,它將被放在參數(shù)里元素的后面。
請看下面的HTM
<div class="container"> <h2>Greetings</h2> <div class="inner">Hello</div> <div class="inner">Goodbye</div> </div>
我們可以創(chuàng)建內(nèi)容然后同時插在好幾個元素后面:
$('.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>
我們也可以在頁面上選擇一個元素然后插在另一個元素后面:
$('.container').after($('h2'));
如果一個被選中的元素被插在另外一個地方,這是移動而不是復(fù)制:
<div class="container"> <div class="inner">Hello</div> <div class="inner">Goodbye</div> </div> <h2>Greetings</h2>
如果有多個目標(biāo)元素,內(nèi)容將被復(fù)制然后被插入到每個目標(biāo)后面。
插入分離的DOM節(jié)點(diǎn)
對于jQuery 1.4, .before()和.after()同時也會對分離的DOM元素有效。例如,下面的代碼:
$('<div/>').after('<p></p>');
結(jié)果是一個包含一個div和一個段落的JQuery集合。因此,我們可以更進(jìn)一步操作這個集合,即使在將它插入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>
對于jQuery 1.4, .after()允許我們傳入一個函數(shù),改函數(shù)返回要被插入的元素。
$('p').after(function() {
return '<div>' + this.className + '</div>';
});
上面的代碼在每個段落后插入一個<div>,<div>里面是該段落的class名稱。
例子:
例如: 在所有的段落后插入一些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:
例如:在所有的段落后插入一個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:
例如:在所有段落后插入一個jQuery對象。
<!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>