我想隐藏最接近点击按钮的跨度,并隐藏按钮.
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>
Run Code Online (Sandbox Code Playgroud)
脚本
$('.btn').click(function(){
$(this).hide();
$(this).next("span").hide();
});
Run Code Online (Sandbox Code Playgroud)
我尝试过以下内容:
1. $(this).next("span").hide();
2. $(this).closest("span").hide();
Run Code Online (Sandbox Code Playgroud)
它只有在我调用所有span元素时才有效.
编辑:跨度很远,因为在我们到达跨度之前还有其他元素,如5-10个元素.
这就是你需要的:JSFiddle
$(this).nextAll("span").first().hide();
Run Code Online (Sandbox Code Playgroud)
nextAll()将看看所有下一个兄弟姐妹(而不仅仅是下一个兄弟姐妹),然后我们只想要找到的第一个跨栏... first()实现了
此外,closest()它不会起作用,因为它正在查找树,而不是在兄弟姐妹.