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
廣告