[英]jQuery getting closest sibling element from $(this) not working
I want to hide the span closest to the button clicked and also hide the button. 我想隐藏最接近单击的按钮的跨度,也要隐藏按钮。
The html goes like this 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>
Script 脚本
$('.btn').click(function(){
$(this).hide();
$(this).next("span").hide();
});
I've tried the following below: 我已经尝试了以下方法:
1. $(this).next("span").hide();
2. $(this).closest("span").hide();
It only works if I call all the span elements. 仅当我调用所有span元素时才有效。
EDIT: the span is quite far as there are other elements like 5-10 elements before we reach the span. 编辑:跨度是相当远的,因为在达到跨度之前还有5-10个其他元素。
This is what you need: JSFiddle 这是您需要的: JSFiddle
$(this).nextAll("span").first().hide();
nextAll()
will look at all the next siblings (rather than just the first next one), and then we only want the first span that is found... first()
achieves that nextAll()
将查看所有下一个同级(而不只是下一个同级),然后我们只希望找到first()
一个跨度... first()
实现
also, closest()
will not work as it is looking up the tree, not at siblings. 同样,
closest()
在查找树时不起作用,而不是在同级树上。
EDIT 2: this answer selects the first siblings span, not the first sibling span after the button. 编辑2:此答案选择第一个同级跨度,而不是按钮后的第一个同级跨度。 The answer above using
$(this).nextAll('span').first().hide()
is the best answer. 上面使用
$(this).nextAll('span').first().hide()
的答案是最好的答案。
$('.btn').click(function(){
$(this).hide();
$(this).siblings("span").first().hide();
});
closest()
looks up the DOM tree, find()
looks down, and siblings()
is what you're looking for. closest()
查找DOM树, find()
向下查找,而siblings()
正是您要寻找的。
Edit 1: added first()
after siblings()
to only select the first one 编辑1:在
siblings()
之后添加first()
siblings()
以仅选择第一个
you can try this way: 您可以这样尝试:
$('.btn').click(function(){
var _that=$(this)
_that.hide();
_that.parent().find('*').eq(_that.index()+2).hide();
});
https://jsfiddle.net/3z5oyc4n/ https://jsfiddle.net/3z5oyc4n/
+2 is for each element after your .btn (+1 = div, +2 = span) .btn之后的每个元素+2(+1 = div,+ 2 = span)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.