jQuery中append()與appendto()用法分析


本文實例分析了jquery中append()與appendto()的用法。分享給大家供大家參考。具體分析如下:

在jQuery的文檔操作方法中,append()和appentto()方法執行的任務相同,但是兩者也有區別。

1、append()方法:在被選元素的結尾(但仍在元素內部)插入指定的內容。

a、語法:

代碼如下:

$(selector).append(content);

 其中,參數content是必需的,指定要附加的內容。

 

b、append能夠使用函數給被選元素附加內容,語法為:

代碼如下:

$(selector).append(function(index,html));

 其中,function()是必需的,參數index和html都是可選的。index表示接收選擇器的index位置,html表示接收選擇器的當前html。

例子:

代碼如下:

 1 <html> 
 2 <head> 
 3 <script type="text/javascript" src="/jquery/jquery.js"></script> 
 4 <script type="text/javascript"> 
 5 $(document).ready(function(){ 
 6   $("button").click(function(){ 
 7     $("p").append(" <b>Hello jQuery!</b>"); 
 8   }); 
 9 }); 
10 </script> 
11 </head> 
12 <body> 
13 <p>This is a paragraph.</p> 
14 <p>This is another paragraph.</p> 
15 <button>在每個 p 元素的結尾添加內容</button> 
16 </body> 
17 </html>

運行結果如下:

This is a paragraph. Hello jQuery!
This is another paragraph. Hello jQuery!

2、appendto()方法:在被選元素的結尾(但仍在元素的內部)插入指定的內容。但不能使用函數來附加內容。

語法:

代碼如下:

$(content).appendto(selector);

 例子:

代碼如下:

 1 <html> 
 2 <head> 
 3 <script type="text/javascript" src="/jquery/jquery.js"></script> 
 4 <script type="text/javascript"> 
 5 $(document).ready(function(){ 
 6   $("button").click(function(){ 
 7     $("<b> Hello jQuery!</b>").appendTo("p"); 
 8   }); 
 9 }); 
10 </script> 
11 </head> 
12 <body> 
13 <p>This is a paragraph.</p> 
14 <p>This is another paragraph.</p> 
15 <button>在每個 p 元素的結尾添加內容</button> 
16 </body> 
17 </html>

運行結果如下:

This is a paragraph. Hello jQuery!
This is another paragraph. Hello jQuery!

希望本文所述對大家的jQuery程序設計有所幫助。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM