jQuery append()方法用法介绍

2021年3月11日17:48:57 发表评论 711 次浏览

这个append()方法在jQuery中, 用于在所选元素的末尾插入一些内容。

语法如下:

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

参数:此方法接受上面提到和下面描述的两个参数:

  • 内容:它是必需的参数, 用于指定要在所选元素的末尾插入的内容。内容的可能值为HTML元素, jQuery对象和DOM元素。
  • 函数(索引, html):它是可选参数, 用于指定将返回要插入的内容的函数
    • 指数:它用于返回元素的索引位置。
    • 的HTML:它用于返回所选元素的当前HTML。

范例1:本示例将内容附加在段落和列表的末尾。

<!DOCTYPE html>
< html >
      
< head >
     < title >
         jQuery append() Method
     </ title >
      
     < script src="
https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
     </ script >
      
     <!-- Script to append content -->
     < script >
         $(document).ready(function(){
             $("#btn1").click(function(){
                 $("p").append(" < b >Append Geeks</ b >.");
             });
            
             $("#btn2").click(function(){
                 $("ol").append("< li >Append Gfg</ li >");
             });
         });
     </ script >
</ head >
  
< body >
     < h1 style = "margin-left: 150px;" >Geeks</ h1 >
      
     < p >lsbin</ p >
     < p >Jquery</ p >
   
     < ol >
         < li >Gfg 1</ li >
         < li >Gfg 2</ li >
         < li >Gfg 3</ li >
     </ ol >
   
     < button id = "btn1" >Append Geeks</ button >
     < button id = "btn2" >Append Gfg</ button >
</ body >
  
</ html >

输出如下:

在单击按钮之前:

jQuery | append()方法1

单击按钮后:

jQuery | append()方法2
jQuery | append()方法3

范例2:本示例将内容附加在段落的末尾。

<!DOCTYPE html>
< html >
      
< head >
     < title >
         jQuery append() Method
     </ title >
      
     < script src="
https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
     </ script >
      
     <!-- Script to append content -->
     < script >
         $(document).ready(function() {
             $("button").click(function() {
                 $("p").append(function(n) {
                     return "< b >   Index of Element is "
                             + n + ".</ b >";
                 });
             });
         });
     </ script >
</ head >
  
< body >
     < h1 style = "margin-left:150px;" >Geeks</ h1 >
      
     < p >Geeks for Geeks</ p >
     < p >Jquery_append</ p >
   
     < button >
         Insertion using Append Method()
     </ button >
</ body >
  
</ html >

输出如下:

在单击按钮之前:

jQuery | append()方法4

单击按钮后:

jQuery | append()方法5

木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: