.prependTo()
.prependTo( target ) Returns: jQuery
描述:將所有元素插入到目標(biāo)前面(元素內(nèi))。
-
version added: 1.0.prependTo( target )
target一個(gè)選擇符,元素,HTML字符串或者jQuery對(duì)象;符合的元素們會(huì)被插入到由參數(shù)指定的目標(biāo)的開頭。
.prepend()和.prependTo()實(shí)現(xiàn)同樣的功能,主要的不同時(shí)語法,插入的內(nèi)容和目標(biāo)的位置不同。對(duì)于 .prepend(),函數(shù)前面的是插入的容器,參數(shù)是內(nèi)容。而.prependTo()剛好相反。
請(qǐng)看下面的HTML
<h2>Greetings</h2> <div class="container"> <div class="inner">Hello</div> <div class="inner">Goodbye</div> </div>
我們可以創(chuàng)建內(nèi)容然后同時(shí)插入到好幾個(gè)元素里面:
$('<p>Test</p>').prependTo('.inner');
結(jié)果如下:
<h2>Greetings</h2>
<div class="container">
<div class="inner">
<p>Test</p>
Hello
</div>
<div class="inner">
<p>Test</p>
Goodbye
</div>
</div>
我們也可以在頁面上選擇一個(gè)元素然后插在另一個(gè)元素里面:
$('h2').prependTo($('.container'));
如果一個(gè)被選中的元素被插入到另外一個(gè)地方,這是移動(dòng)而不是復(fù)制:
<div class="container"> <h2>Greetings</h2> <div class="inner">Hello</div> <div class="inner">Goodbye</div> </div>
如果有多個(gè)目標(biāo)元素,內(nèi)容將被復(fù)制然后插入到每個(gè)目標(biāo)里面。
例子
將所有span插入到ID為“foo”的元素前面。
<!DOCTYPE html>
<html>
<head>
<style>div { background:yellow; }</style>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
</head>
<body>
<div id="foo">FOO!</div>
<span>I have something to say... </span>
<script>$("span").prependTo("#foo"); // check prepend() examples</script>
</body>
</html>