jquery选择相邻若干兄弟元素

这篇博客介绍如何使用jQuery实现点击切换效果,仅影响含有'father'类的行及其相邻的'son'子行,而不影响其他'son'元素。通过选择并遍历'father'的兄弟元素来实现这一目标。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

实现点击是显示表格,再次点击隐藏类名father下的son.对相邻的兄弟元素son没有影响。

html代码:

<table class="table">

<thead>

<tr>

<th>名称</th>

<th>城市</th>

</tr>

</thead>

<tbody>

<tr class="father">

<td>Tanmay</td>

<td>Bangalore</td>

</tr>

<tr class="son">

<td>Sachin</td>

<td>Mumbai</td>

</tr>

<tr class="son">

<td>Sachin</td>

<td>Mumbai</td>

</tr>

<tr class="son">

<td>Sachin</td>

<td>Mumbai</td>

</tr>

<tr class="father">

<td>Tanmay</td>

<td>Bangalore</td>

</tr>

<tr class="son">

<td>Sachin</td>

<td>Mumbai</td>

</tr>

</tbody>

</table>

思路:即选择两个father之间的兄弟元素,先选择到点击事件的father的所有兄弟元素,然后利用循环函数each()逐个循环匹配,遇到father,跳出循环。


<script>

                $(document).ready(function() {
                    $('.father').click(function(){
                        var e = $(this).nextAll();     
                       e.each(function(index, el) {
                           if(
                            $(this).attr("class")=='son'){
                             $(this).slideToggle();
                           }else{
                            return false;
                           }
                       });
                    })
                });
                    
                </script>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值