jQuery:如何获取父级的特定子级?
举一个简化的例子,我在页面上多次重复以下块(它是动态生成的):
<div class="box">
<div class="something1"></div>
<div class="something2">
<a class="mylink">My link</a>
</div>
</div>
单击时,我可以通过以下方式到达链接的父级:
$(".mylink").click(function() {
$(this).parents(".box").fadeOut("fast");
});
但是...我需要到达该特定父级的
。基本上,有人可以告诉我如何在无法直接引用的情况下引用更高级别的兄弟姐妹吗?我们就称呼它为大哥吧。直接引用老大哥的类名会导致页面上该元素的每个实例淡出 - 这不是所需的效果。
我试过了:
parents(".box .something1") ... no luck.
parents(".box > .something1") ... no luck.
siblings() ... no luck.
有人吗?谢谢。
To give a simplified example, I've got the following block repeated on the page lots of times (it's dynamically generated):
<div class="box">
<div class="something1"></div>
<div class="something2">
<a class="mylink">My link</a>
</div>
</div>
When clicked, I can get to the parent of the link with:
$(".mylink").click(function() {
$(this).parents(".box").fadeOut("fast");
});
However... I need to get to the <div class="something1">
of that particular parent.
Basically, can someone tell me how to refer to a higher-level sibling without being able to refer to it directly? Let's call it big brother. A direct reference to the big brother's class name would cause every instance of that element on the page to fade out - which is not the desired effect.
I've tried:
parents(".box .something1") ... no luck.
parents(".box > .something1") ... no luck.
siblings() ... no luck.
Anyone? Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
调用
.parents(".box .something1")
将返回与选择器.box .something
匹配的所有父元素。换句话说,它将返回.something1
且位于.box
内部的父元素。您需要获取最近父级的子级,如下所示:
此代码调用
.closest
获取与选择器匹配的最内层父元素,然后在该父元素上调用.children
来查找您要查找的叔叔。Calling
.parents(".box .something1")
will return all parent elements that match the selector.box .something
. In other words, it will return parent elements that are.something1
and are inside of.box
.You need to get the children of the closest parent, like this:
This code calls
.closest
to get the innermost parent matching a selector, then calls.children
on that parent element to find the uncle you're looking for.树遍历很有趣,
还有更多方法,您可能会发现这些文档很有帮助。
Tree traversal is fun
And much more ways, you might find these docs helpful.
这将找到第一个具有
box
类的父类,然后找到第一个具有正则表达式匹配something
的子类并获取 id。This will find the first parent with class
box
then find the first child class with regex matchingsomething
and get the id.如果我正确理解您的问题,
$(this).parents('.box').children('.something1')
这是您要找的吗?If I understood your problem correctly,
$(this).parents('.box').children('.something1')
Is this what you are looking for?您可以将
.each()
与.children()
和括号内的选择器一起使用:You could use
.each()
with.children()
and a selector within the parenthesis: