jQuery last()函数和使用示例

2021年3月17日17:11:38 发表评论 706 次浏览

last()函数是jQuery中的内置函数, 用于查找指定元素的最后一个元素

语法如下:

$(selector).last()

选择器是选定的元素。

参数:

它不接受任何参数。

返回值:

它返回所选元素中的最后一个元素

JavaScript代码显示此功能的工作方式:

代码1:

< html >
    < head >
       < script src =
"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js" >
       </ script >
       < script >
          $(document).ready(function(){
             $("p").last().css("background-color", "lightgreen");
          });
       </ script >
    </ head >
    < body >
       < h1 >Welcome to lsbin !!!</ h1 >
       < p style = "padding:5px; border:1 px solid green" >
         This is the First.</ p >
       < p style = "padding:5px; border:1 px solid green" >
         This is the Second.</ p >
       < p style = "padding:5px; border:1 px solid green" >
         This is the Third.</ p >
       < br >
    </ body >
</ html >

在这段代码中, 最后一个的背景色

" p"

元素得到改变。

输出如下:

jQuery | last()与示例1

代码2:

< html >
  
< head >
     < script src =
"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js" >
     </ script >
     < script >
         $(document).ready(function() {
             $(".main").last().css("background-color", "lightgreen");
         });
     </ script >
</ head >
  
< body >
     < h1 >Welcome to lsbin !!!</ h1 >
     < div class = "main" style = "border: 1px solid green;" >
         < p >This is the First.</ p >
     </ div >
     < br >
     < div class = "main" style = "border: 1px solid green;" >
         < p >This is the Second.</ p >
     </ div >
     < br >
     < div style = "border: 1px solid green;" >
         < p >This is the Third.</ p >
     </ div >
     < br >
</ body >
  
</ html >

在上面的示例中, 类" main"的最后一个元素被突出显示。

输出如下:

jQuery | last()与示例2

木子山

发表评论

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