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


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


:nth-last-of-type()選擇器用於選擇具有相同元素名稱的父級的所有子級,從最後到第一個開始計數。它使用1索引計數。

用法:

element:nth-last-of-type(n|even|odd|formula)

參數:



  • n:它從最後選擇第n個元素。
  • even:它從最後選擇每個偶數元素。
  • odd:它從最後選擇每個奇數元素。
  • formula:它包含從最後開始生成元素分組的公式,例如:3n + 2通過取值n-0、1、2,...來選擇此表達式輸出的每個元素。

範例1:此示例使用:nth-last-of-type()選擇器從最後選擇奇數元素。

<!DOCTYPE html> 
<html> 
      
<head> 
    <title> 
        jQuery |:nth-last-of-type() Selector 
    </title> 
      
    <script src= 
"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> 
    </script> 
</head> 
  
<body> 
    Computer Science Subjects 
    <ul> 
        <li>Data Structure</li> 
        <li>Algorithm Analysis</li> 
        <li>Operating System</li> 
        <li>Computer Networks</li> 
        <li>Web Technology</li> 
        <li>C Programming</li> 
        <li>C++ Programming</li> 
        <li>Java</li> 
    </ul> 
      
    <!-- Script to use:nth-last-of-type() Selector -->
    <script> 
        $(document).ready(function() { 
            var el = $("ul li:nth-last-of-type(odd)").css({ 
                background:"green" 
            }); 
        }); 
    </script> 
</body> 
  
</html>                    

輸出

範例2:本示例使用:nth-last-of-type()選擇器選擇最後一個元素。

<!DOCTYPE html> 
<html> 
      
<head> 
    <title> 
        jQuery |:nth-last-of-type() Selector 
    </title> 
      
    <script src= 
"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> 
    </script> 
</head> 
  
<body> 
    <section> 
        <article> 
            <p>Company - GeeksforGeeks</p> 
            <p>Name - ABC</p> 
            <p>Email - abc@geeksforgeeks.org</p> 
        </article> 
        <article> 
                <p>Company - GFG</p> 
                <p>Name - XYZ</p> 
                <p>Email - xyz@gfg.org</p> 
        </article> 
        <article> 
                <p>Company - G4G</p> 
                <p>Name - Geeks</p> 
                <p>Email - geeks@g4g.org</p> 
        </article> 
    </section> 
      
    <!-- Script to use:nth-last-of-type() selector -->
    <script> 
        $(document).ready(function() { 
            $("article p:first-of-type").css({ 
                fontWeight:"bold", 
                fontSize:'1.2rem' 
            }) 
            $("article p:nth-last-of-type(1)").css({ 
                fontStyle:'italic', 
                opacity:0.8 
            }) 
        }) 
    </script> 
<body> 
      
</html>                    

輸出:




相關用法


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