繁体   English   中英

jQuery从$(this)获取最近的同级元素不起作用

[英]jQuery getting closest sibling element from $(this) not working

我想隐藏最接近单击的按钮的跨度,也要隐藏按钮。

HTML是这样的

<!-- the div will be looped using php -->
<!-- this will only be a general idea of the code as the actual is very long and messy -->
<div>       
  <form><!-- This is like the head section -->
    <div>
        <div> <!-- some divs -->
            <button class="btn"></button> <!-- where i want it to work -->
                <div></div><!-- make this 5 times -->
            <span>content to hide</span>
        </div>
    </div>
  </form>      
  <div><!-- Comments to the head are here -->
    <button class="btn"></button><!-- button where it works -->
    <span>contains the comments</span>
  </div>
</div>

脚本

$('.btn').click(function(){
    $(this).hide();
    $(this).next("span").hide();
});

我已经尝试了以下方法:

1. $(this).next("span").hide(); 
2. $(this).closest("span").hide();

仅当我调用所有span元素时才有效。

编辑:跨度是相当远的,因为在达到跨度之前还有5-10个其他元素。

这是您需要的: JSFiddle

$(this).nextAll("span").first().hide();

nextAll()将查看所有下一个同级(而不只是下一个同级),然后我们只希望找到first()一个跨度... first()实现

同样, closest()在查找树时不起作用,而不是在同级树上。

编辑2:此答案选择第一个同级跨度,而不是按钮后的第一个同级跨度。 上面使用$(this).nextAll('span').first().hide()的答案是最好的答案。

$('.btn').click(function(){
    $(this).hide();
    $(this).siblings("span").first().hide();
});

closest()查找DOM树, find()向下查找,而siblings()正是您要寻找的。

编辑1:在siblings()之后添加first() siblings()以仅选择第一个

您可以这样尝试:

$('.btn').click(function(){
    var _that=$(this)
    _that.hide();
    _that.parent().find('*').eq(_that.index()+2).hide();
});

https://jsfiddle.net/3z5oyc4n/

.btn之后的每个元素+2(+1 = div,+ 2 = span)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM