在jQuery的文檔操作方法中,append()和appentto()方法執行的任務相同,但是兩者也有區別。
1、append()方法:在被選元素的結尾(但仍在元素內部)插入指定的內容。
a、語法:$(selector).append(content); 其中,參數content是必需的,指定要附加的內容。
b、append能夠使用函數給被選元素附加內容,語法爲:$(selector).append(function(index,html)); 其中,function()是必需的,參數index和html都是可選的。index表示 接收選擇器的index位置,html表示接收選擇器的當前html。
例子:
<html> <head> <script type="text/javascript" src="/jquery/jquery.js"></script> <script type="text/javascript"> $(document).ready(function(){ $("button").click(function(){ $("p").append(" <b>Hello jQuery!</b>"); }); }); </script> </head> <body> <p>This is a paragraph.</p> <p>This is another paragraph.</p> <button>在每個 p 元素的結尾添加內容</button> </body> </html>結果:
This is a paragraph. Hello jQuery!
This is another paragraph. Hello jQuery!
2、appendto()方法:在被選元素的結尾(但仍在元素的內部)插入指定的內容。但不能使用函數來附加內容。
語法:$(content).appendto(selector);
例子:
<html>
<head>
<script type="text/javascript" src="/jquery/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("button").click(function(){
$("<b> Hello jQuery!</b>").appendTo("p");
});
});
</script>
</head>
<body>
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
<button>在每個 p 元素的結尾添加內容</button>
</body>
</html>
結果:
This is a paragraph. Hello jQuery!
This is another paragraph. Hello jQuery!