.append()
.append( content ) 返回:jQuery
描述:根據(jù)參數(shù)設定在每個匹配元素里面的末尾處插入內(nèi)容。
-
version added: 1.0.append( content )
content一個元素,HTML字符串,或者jQuery對象,用來插在每個匹配元素里面的末尾。
-
version added: 1.4.append( function(index, html) )
function(index, html)一個返回HTML字符串的函數(shù),該字符串用來插入到匹配元素的末尾。 Receives the index position of the element in the set and the old HTML value of the element as arguments.
.append()函數(shù)將特定內(nèi)容插入到每個匹配元素里面的最后面,作為它的最后一個子元素(last child),
(如果要作為第一個子元素 (first child), 用.prepend()).
.append() 和.appendTo()實現(xiàn)同樣的功能。主要的不同是語法——內(nèi)容和目標的位置不同。對于.append(),
選擇表達式在函數(shù)的前面,參數(shù)是將要插入的內(nèi)容。對于.appendTo()剛好相反,內(nèi)容在方法前面,它將被放在參數(shù)里元素的末尾。
請看下面的HTML:
<h2>Greetings</h2> <div class="container"> <div class="inner">Hello</div> <div class="inner">Goodbye</div> </div>
我們可以創(chuàng)建內(nèi)容然后同時插入到好幾個元素里面:
$('.inner').append('<p>Test</p>');
每個新的inner <div>元素會得到新的內(nèi)容:
<h2>Greetings</h2>
<div class="container">
<div class="inner">
Hello
<p>Test</p>
</div>
<div class="inner">
Goodbye
<p>Test</p>
</div>
</div>
我們也可以在頁面上選擇一個元素然后插在另一個元素里面:
$('.container').append($('h2'));
如果一個被選中的元素被插入到另外一個地方,這是移動而不是復制:
<div class="container"> <div class="inner">Hello</div> <div class="inner">Goodbye</div> <h2>Greetings</h2> </div>
如果有多個目標元素,內(nèi)容將被復制然后按順序插入到每個目標里面。
例子:
Example: 在所有的段落里插入一些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").append("<strong>Hello</strong>");
</script>
</body>
</html>
Demo:
Example: 在所有段落里插入元素。
<!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").append(document.createTextNode("Hello"));
</script>
</body>
</html>
Demo:
Example: 在所有段落里插入jQuery對象 (jQuery對象類似于一組DOM元素)
<!DOCTYPE html>
<html>
<head>
<style>
p { background:yellow; }
</style>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
</head>
<body>
<strong>Hello world!!!</strong><p>I would like to say: </p>
<script>
$("p").append( $("strong") );
</script>
</body>
</html>