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>
输出:
在上面的例子中,它们的父级元素(这里的p标签)的所有唯一子元素(这里的div标签)都被格式化为绿色,即 “第二个div的唯一Geek。”和 “第三个div的唯一Geek”。
示例 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标签)都被格式化为绿色,即 “The only Geek of id.”、”The only Geek of class. “和 “The only Geek of body.”,因为每个段落标签都被认为是每个父级的不同孩子。