当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。