Jquery教程
Jquery动效
Jquery HTML/CSS
Jquery 事件
jquery常用

Jquery siblings()方法

顾名思义, siblings()方法返回所选元素的所有兄弟姐妹。它是jQuery中的内置方法。兄弟姐妹是具有共同父对象的那些元素。
假设我们有一个jQuery对象代表元素集,因此 siblings()方法将搜索同级元素中的兄弟姐妹。 DOM树并构造一个包含匹配元素的新jQuery对象。

语法

$(selector).siblings(filter)
此方法接受名为 filter 的可选参数,定义如下。
filter: 选择器表达式,用于缩小对同级元素的搜索范围。它可以具有多个值。值应该用逗号分隔。
假设有一个包含多个同级元素的段落元素,我们必须找到 h2 span ,则可以如下编写。
$("p").siblings("h2, span")
上述语法只会返回 p 元素同级的 h2 span 元素。

Example1

在此示例中,有一个具有多个子元素的父div元素。在这里,我们使用 siblings()方法来查找 span 元素的同级。 span 元素及其兄弟姐妹共享公共父元素 div 元素。
在这里,我们没有使用siblings()方法的可选参数。我们必须单击给定的按钮以获取 span 元素的同级元素。
<html>
<head>
<style>
div{
border: 2px solid black;
}
.d1 *{
display: block;
border: 2px solid black;
color: black;
padding: 5px;
margin: 15px;
}
</style>
<script src="/ajax/libs/jquery/3.5.1/jquery.min.js"> </script>
<script>
$(document).ready(function() {
$("button").click(function() {
$("span").siblings().css({ "color": "red", "border": "2px dashed blue"});
});
});
</script>
</head>
<body>
<h4> This is an example of using the jQuery's siblings() method. </h4>
<div class = "d1">
This is parent div element
<p> This is first paragraph </p>
<p> This is second paragraph </p>
<span> This is span </span>
<h4> This is heading h4 </h4>
<h2>This is heading h2 </h2>
</div>
<p> Click the following button to get the siblings. </p>
<button> Click me </button>
</body>
</html>
输出:
执行上述代码后,输出将为-
jQuery siblings()方法
单击给定按钮后,输出为-
jQuery siblings()方法

Example2

在此示例中,我们使用了 siblings()方法。在这里,我们指定了 filter 参数的多个值。
此参数缩小了搜索范围并找到了 h2 span 元素的strong>和 p 兄弟姐妹。
<html>
<head>
<style>
div{
border: 2px solid black;
}
.d1 *{
display: block;
border: 2px solid black;
color: black;
padding: 5px;
margin: 15px;
}
</style>
<script src="/ajax/libs/jquery/3.5.1/jquery.min.js"> </script>
<script>
$(document).ready(function() {
$("button").click(function() {
$("span").siblings("h2, p").css({ "color": "red", "border": "2px dashed blue"});
});
});
</script>
</head>
<body>
<h4> This is an example of using the jQuery's siblings() method. </h4>
<div class = "d1">
This is parent div element
<p> This is first paragraph </p>
<p> This is second paragraph </p>
<span> This is span </span>
<h4> This is heading h4 </h4>
<h2>This is heading h2 </h2>
</div>
<p> Click the following button to get the siblings. </p>
<button> Click me </button>
</body>
</html>
输出:
执行上述代码后,输出将为-
jQuery siblings()方法
单击给定按钮后,输出为-
jQuery siblings()方法
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4