jquery 获取同级元素
In this post, we will discuss how to get the siblings of an HTML element in jQuery. jQuery API provides siblings()
method to achieve this functionality.
在本文中,我们将讨论如何在jQuery中获取HTML元素的同级元素。 jQuery API提供了siblings()
方法来实现此功能。
jQuery兄弟姐妹() (jQuery siblings())
The siblings() method is used to return all the siblings of the selected HTML element. Unlike jQuery next()
and prev()
methods, this method traverses both forward and backwards along the siblings of the selected element. This method is very handy when you want to carry out similar tasks on a set of elements.
siblings()方法用于返回所选HTML元素的所有同级对象。 与jQuery next()
和prev()
方法不同,此方法沿选定元素的同级对象向前和向后遍历。 当您要对一组元素执行类似任务时,此方法非常方便。
Here is the general syntax for using siblings method:
这是使用兄弟姐妹方法的一般语法:
- selector.siblings( [filter ] ) selector.siblings([ 过滤器 ])
filter is an optional parameter passed to the method to narrow down the traversal.
filter是传递给该方法的可选参数,以缩小遍历范围。
jQuery siblings()示例 (jQuery siblings() example)
Following example demonstrates the jQuery siblings() usage.
以下示例演示了jQuery siblings()的用法。
<!doctype html>
<html>
<head>
<title>jQuery Traversing siblings</title>
<style>
span{
color: blue;
margin: 30px;
font-size: 16px;
padding: 5px;
font-weight: bolder;
border: 1px solid lightgrey;
}
.highlight{
background: yellow;
}
div{
display: block;
border: 3px solid lightgrey;
color: lightgrey;
padding: 5px;
margin: 25px;
width:350px;
}
</style>
<script src="https://code.jquery/jquery-2.1.1.js"></script>
</head>
<body>
<div>
<span> Bheem</span>
<span class="highlight"> Arjun</span>
<span> Nakul</span>
</div>
<div>
<span> Mark</span>
<span class="highlight"> Tom </span>
<span> Steve</span>
</div>
<div>
<span> Sachin</span>
<span> Saurav</span>
<span> Zaheer </span>
</div>
<script>
$( ".highlight" ).siblings()
.css( "color", "red" );
</script>
</body>
</html>
In this example, you can see three div
elements and each div
has three span
elements. In the first and second div
elements, the second span has a CSS style class “highlight”. The siblings() method returns all the siblings of the selected element having class=”highlight” and changes the color of the siblings to red.
在此示例中,您可以看到三个div
元素,每个div
具有三个span
元素。 在第一个和第二个div
元素中,第二个跨度具有CSS样式类“ highlight” 。 siblings()方法返回具有class =“ highlight”的所选元素的所有同级并将同级颜色更改为红色。
In the firstdiv
, Bheem and Nakul are siblings of Arjun and in the second div
, Mark and Steve are siblings of Tom. This is how we get the siblings of an element in jQuery. Below image is the output produced by the above HTML page.
在第一个div
,Bheem和纳库尔是阿琼的兄弟姐妹,在第二div
, 马克和史蒂夫是汤姆的兄弟姐妹。 这就是我们获取jQuery中元素的同级的方式。 下图是以上HTML页面产生的输出。
翻译自: https://www.journaldev/5301/how-to-get-the-siblings-of-an-element-in-jquery
jquery 获取同级元素
更多推荐
jquery 获取同级元素_如何在jQuery中获取元素的同级
发布评论