jQuery :only-of-type 选择器



jQuery 中的:only-of-type 选择器用于选择在其父元素内是其类型中唯一子元素的元素。

语法

以下是 jQuery :only-of-type 选择器的语法:

$(":only-of-type")

参数

此选择器目标是其类型在其父元素内唯一子元素的元素。

示例

在下面的示例中,我们使用 jQuery :only-of-type 选择器来选择每个<p>元素,该元素是其父元素(<div>)中唯一的<p>元素:

<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script>
        $(document).ready(function(){
            $("p:only-of-type").css("background-color", "yellow");
        });
    </script>
</head>
<body>
    <div style="border: 1px solid black;">
        <p>This paragraph is the only one of its type within the parent div.</p>
        <p>This paragraph is another paragraph within the parent div.</p>
    </div><br>
    <div style="border: 1px solid black;">
        <p>This paragraph is the only one of its type within the parent div.</p>
    </div><br>
    <div style="border: 1px solid black;">
        <p>This paragraph is the only one of its type within the parent div.</p>
    </div>
</body>
</html>

执行上述程序后,它会将其类型在 div 内唯一的段落应用黄色背景颜色。

jquery_ref_selectors.htm
广告