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


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


:only-of-type選擇器是jQuery中的內置選擇器,用於選擇所有作為其父代唯一子元素的元素。句法:

$("parent_name:only-of-type")

示例1:

<!DOCTYPE html> 
<html> 
  
<head> 
    <script src= 
"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> 
    </script> 
  
    <!-- Script to use only-of-type selector -->
  
    <script> 
        $(document).ready(function() { 
            $("p:only-of-type").css( 
              "color", "green"); 
        }); 
    </script> 
</head> 
  
<body> 
    <center> 
  
        <!-- Division 1 -->
  
        <div style="border:1px solid;"> 
            <p>Geek1 of first div.</p> 
            <p>Geek2 of first div.</p> 
        </div> 
        <br> 
  
        <!-- Division 2 -->
  
        <div style="border:1px solid;"> 
            <p>The only Geek of second div.</p> 
        </div> 
        <br> 
  
        <!-- Division 3 -->
  
        <div style="border:1px solid;"> 
            <span>GeeksforGeeks</span> 
            <p>The only Geek of third div.</p> 
        </div> 
    </center> 
</body> 
  
</html>

輸出:



在上麵的示例中,其父項(此處為div標簽)的所有唯一子元素(此處為d標簽)被格式化為綠色,即“第二個div的唯一怪胎”。和“第三分區的唯一怪胎”。

示例2:

<!DOCTYPE html> 
<html> 
  
<head> 
    <script src= 
"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> 
    </script> 
  
    <!-- Script to use only-of-type selector -->
  
    <script> 
        $(document).ready(function() { 
            $("p:only-of-type").css( 
              "color", "green"); 
        }); 
    </script> 
</head> 
  
<body> 
    <center> 
  
        <!-- Children of division -->
  
        <h3>Division as a parent</h3> 
        <div> 
            <p>Geek1 of div.</p> 
            <p>Geek2 of div.</p> 
        </div> 
  
        <!-- Only child of id -->
  
        <h3>ID as a parent.</h3> 
        <id> 
            <p>The only Geek of id.</p> 
        </id> 
  
        <!-- Only child of class -->
  
        <h3>Class as a parent.</h3> 
        <class> 
            <p>The only Geek of class.</p> 
        </class> 
  
        <!-- Only child of body -->
  
        <h3>Body as a parent.</h3> 
        <p>The only Geek of body.</p> 
    </center> 
</body> 
  
</html>

輸出:

在上麵的示例中,其各自父級的所有唯一子元素(此處為p標簽)被格式化為綠色,即“ id的唯一Geek”,“ class的唯一Geek”。和“唯一的身體怪胎”。因為每個段落標簽都被視為每個父母的不同孩子。




相關用法


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