jQuery html()方法用法介绍和示例

2021年3月15日09:18:13 发表评论 776 次浏览

html()方法在jQuery中, 用于设置或返回所选元素innerHTML内容

语法如下:

  • 它返回第一个匹配元素的内容。
    $(selector).html()
  • 设置匹配元素的内容。
    $(selector).html(content)
  • 它使用功能设置内容。
    $(selector).html(function(index, currentcontent))

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

  • 内容:它是必填参数, 用于为所选元素指定新内容。
  • 函数(索引, 当前内容):它是一个可选参数, 它指定一个函数, 该函数返回所选元素的新内容。
    • 指数:它用于返回元素在集合中的索引位置。
    • 当前内容:它用于返回所选元素的当前HTML内容。

以下示例说明了jQuery中的html()方法:

范例1:本示例将内容设置为元素。

<!DOCTYPE html>
< html >
  
< head > 
     < title >
         jQuery html() Method
     </ title >
        
     < script src =
"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js" >
     </ script >
</ head > 
    
< body style = "text-align:center;" >  
            
     < h1 style = "color:green;" >  
         lsbin
     </ h1 >  
      
     < h2 >
         Fade-in effect< br >
         jQuery | html() Method
     </ h2 >
      
     < button >Click</ button >
      
     < script >
         $(document).ready(function(){
             $("button").click(function(){
                 $("h2").html("Hello < b >GEEKS!</ b >");
             });
         });
     </ script >
</ body >  
  
</ html >

输出如下:

jQuery | html()方法1

范例2:本示例返回element的第一个匹配项。

<!DOCTYPE html>
< html >
  
< head > 
     < title >
         jQuery html() Method
     </ title >
        
     < script src =
"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js" >
     </ script >
</ head > 
    
< body style = "text-align:center;" >  
            
     < h1 style = "color:green;" >  
         lsbin
     </ h1 >  
      
     < h2 >
         jQuery | html() Method
     </ h2 >
      
     < button >Click</ button >
      
     < script >
         $(document).ready(function(){
             $("button").click(function(){
                 alert($("h2").html());
             });
         });
     </ script >
</ body >  
  
</ html >

输出如下:

jQuery | html()方法2

范例3:本示例使用功能设置内容。

<!DOCTYPE html>
< html >
  
< head > 
     < title >
         jQuery html() Method
     </ title >
        
     < script src =
"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js" >
     </ script >
</ head > 
    
< body style = "text-align:center;" >  
            
     < h1 style = "color:green;" >  
         lsbin
     </ h1 >  
      
     < h2 >
         jQuery | html() Method
     </ h2 >
      
     < button >Click</ button >
      
     <!-- Script to set the content -->
     < script >
         $(document).ready(function() {
             $("button").click(function() {
                 $("h2").html(function(n) {
                     return "jQuery | html() Method"
                             + " has index: " + n;
                 });
             });
         });
     </ script >
</ body >  
</ html >

输出如下:

jQuery | html()方法3

木子山

发表评论

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