當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


jQuery :last-of-type用法及代碼示例


:last-of-type選擇器用於選擇作為其父級的最後一個子級的所有元素。

用法:

$(":last-of-type")

以下示例說明了jQuery中的last-of-type選擇器:



範例1:本示例將其父級的最後一個元素(div標簽)的背景顏色更改為綠色,並將text-color更改為白色。

<!DOCTYPE html>   
<html>   
    <head>  
        <title>  
            jQuery |:last-of-type Selector 
        </title> 
          
        <script src= 
"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> 
        </script> 
          
        <!-- Script to use last-of-type selector -->
        <script> 
            $(document).ready(function() { 
                $("h4:last-of-type").css({ 
                    "background-color":"green",  
                    "color":"white" 
                }); 
            }); 
        </script> 
          
        <!-- CSS property to set style of element -->
        <style> 
           option { 
            font-weight:bold; 
            font-size:25px; 
            color:green; 
           } 
           select { 
            font-weight:bold; 
            font-size:25px; 
            color:green; 
           } 
        </style> 
    </head>  
      
    <body style="text-align:center;">   
        <h1>   
            jQuery |:last-of-type Selector 
        </h1>  
          
        <div style= "border:1px solid blue;"> 
            <h4>The first heading in first div.</h4> 
            <h4>The last heading in first div.</h4> 
        </div><br> 
   
        <div style= "border:1px solid blue;"> 
            <h4>The first heading in second div.</h4> 
            <h4>The last heading in second div.</h4> 
        </div> 
    </body>   
</html>    

輸出:

範例2:本示例將<body>標簽的最後一個標題的背景顏色更改為綠色,並將text-color更改為白色。

<!DOCTYPE html>   
<html>   
    <head>  
        <title>  
            jQuery |:last-of-type Selector 
        </title> 
          
        <script src= 
"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> 
        </script> 
          
        <!-- Script to use last-of-type selector -->
        <script> 
            $(document).ready(function() { 
                $("h4:last-of-type").css({ 
                    "background-color":"green",  
                    "color":"white" 
                }); 
            }); 
        </script> 
          
        <style> 
            option { 
                font-weight:bold; 
                font-size:25px; 
                color:green; 
            } 
            select { 
                font-weight:bold; 
                font-size:25px; 
                color:green; 
            } 
        </style> 
    </head>  
      
    <body style="text-align:center;">   
        <h1>   
            jQuery |:last-of-type Selector 
        </h1>   
        <h4>The first heading in body.</h4> 
   
        <h4>The last heading in body.</h4> 
              
    </body>   
</html>      

輸出:




相關用法


注:本文由純淨天空篩選整理自PranchalKatiyar大神的英文原創作品 jQuery | :last-of-type Selector。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。