jQuery如何使用:first选择器?代码实例

2021年3月20日16:34:21 发表评论 607 次浏览

它是一个jQuery选择器用于选择指定类型的第一个元素。

语法如下:

$(":first")

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

示例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:first").css(
               "background-color", "green");
         });
     </ script >
</ head >
  
< body >
  
     < p >Geeks for Geeks</ p >
     < p >jQuery</ p >
     < p >First Selector</ p >
  
</ body >
  
</ html >

输出如下:

jQuery如何使用:first选择器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:first").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 >First Selector</ p >
     </ div >
  
     < p >jQuery:First Selector</ p >
  
</ body >
  
</ html >

输出如下:

jQuery如何使用:first选择器2

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


木子山

发表评论

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