.insertBefore()
.insertBefore( target ) 返回:jQuery
Description: 在目標(biāo)前插入所有匹配元素。
-
version added: 1.0.insertBefore( target )
target一個(gè)選擇器,元素,THML字符串或者jQuery對(duì)象,匹配的元素將會(huì)被插入在由參數(shù)指定的目標(biāo)后面。
The .before()和.insertBefore()實(shí)現(xiàn)同樣的功能。主要的區(qū)別是語(yǔ)法——內(nèi)容和目標(biāo)的位置。對(duì)于 .before(),選擇表達(dá)式在函數(shù)前面,內(nèi)容作為參數(shù),而.insertBefore()剛好相反。
請(qǐng)看下面的HTML:
<div class="container"> <h2>Greetings</h2> <div class="inner">Hello</div> <div class="inner">Goodbye</div> </div>
我們可以創(chuàng)建內(nèi)容然后同時(shí)插在好幾個(gè)元素前面:
$('<p>Test</p>').insertBefore('.inner');
得到新內(nèi)容如下:
<div class="container"> <h2>Greetings</h2> <p>Test</p> <div class="inner">Hello</div> <p>Test</p> <div class="inner">Goodbye</div> </div>
我們也可以在頁(yè)面上選擇一個(gè)元素然后插在另一個(gè)元素前面:
$('h2').insertBefore($('.container'));
如果一個(gè)被選中的元素被插在另外一個(gè)地方,這是移動(dòng)而不是復(fù)制:
<h2>Greetings</h2> <div class="container"> <div class="inner">Hello</div> <div class="inner">Goodbye</div> </div>
如果有多個(gè)目標(biāo)元素,內(nèi)容將被復(fù)制然后被插入到每個(gè)目標(biāo)前面。
例子:
在id為"foo"的元素前面插入段落。和 $("#foo").before("p")一樣。
<!DOCTYPE html>
<html>
<head>
<style>#foo { background:yellow; }</style>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
</head>
<body>
<div id="foo">FOO!</div><p>I would like to say: </p>
<script>$("p").insertBefore("#foo"); // check before() examples</script>
</body>
</html>