jQuery如何使用:last选择器?代码示例

2021年3月18日14:51:48 发表评论 604 次浏览

:last是一个jQuery选择器用于选择指定类型的最后一个元素。

语法如下:

$(":last")

返回值:它选择并返回最后一个元素。

示例1:

<!DOCTYPE html>
< html >
< h1 >
   < center >
     Geeks 
   </ center >
   </ h1 >
  
< 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", "green");
         });
     </ script >
</ head >
  
< body >
  
     < p >Geeks for Geeks</ p >
     < p >jQuery</ p >
     < p >Last Selector</ p >
  
</ body >
  
</ html >

输出如下:

jQuery :last选择器1

示例2:

<!DOCTYPE html>
< html >
< h1 >
   < center >
     Geeks 
   </ center >
   </ h1 >
  
< 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", "green");
         });
     </ script >
</ head >
  
< body >
     < div style = "border:1px solid;" >
         < p >Geeks for Geeks</ p >
         < p >jQuery</ p >
     </ div >
     < br >
  
     < div style = "border:1px solid;" >
         < p >Geeks for Geeks</ p >
         < p >jQuery</ p >
         < p >Last Selector</ p >
     </ div >
  
     < div >jQuery:Last Selector</ div >
  
</ body >
  
</ html >

输出如下:

jQuery :last选择器2

注意:上面的代码将只选择第一个div的最后一个<p>元素。要选择第二个div的最后一个<p>元素, 请使用:last-child选择器。


木子山

发表评论

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