jQuery:如何获得父母的特定孩子? [英] jQuery: How to get to a particular child of a parent?
问题描述
举一个简化的例子,我在页面上多次重复以下代码块(它是动态生成的):
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");
});
但是...我需要转到该特定父级的<div class="something1">
.
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.
我尝试过:
parents(".box .something1") ... no luck.
parents(".box > .something1") ... no luck.
siblings() ... no luck.
有人吗?谢谢.
推荐答案
调用.parents(".box .something1")
将返回与选择器.box .something
匹配的所有父元素.换句话说,它将返回.something1
并且在.box
内部的父元素.
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).closest('.box').children('.something1')
此代码调用 .closest
以获取与选择器匹配的最内层父级,然后调用
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.
这篇关于jQuery:如何获得父母的特定孩子?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!