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");
});

但是... 我需要找到那个特定父母的 <div class="something1">

基本上,有人能告诉我如何在不能直接引用的情况下引用更高级别的兄弟姐妹吗?就叫大哥吧。直接引用老大哥的类名会导致页面上该元素的每个实例淡出——这不是我们想要的效果。

我试过了:

parents(".box .something1") ... no luck.
parents(".box > .something1") ... no luck.
siblings() ... no luck.

有人吗? 谢谢。

281994 次浏览
$(this).parent()

Tree traversal is fun

$(this).parent().siblings(".something1");


$(this).parent().prev(); // if you always want the parent's previous sibling


$(this).parents(".box").children(".something1");

And much more ways, you might find these docs helpful.

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')

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.

If I understood your problem correctly, $(this).parents('.box').children('.something1') Is this what you are looking for?

You could use .each() with .children() and a selector within the parenthesis:

//Grab Each Instance of Box.
$(".box").each(function(i){


//For Each Instance, grab a child called .something1. Fade It Out.
$(this).children(".something1").fadeOut();
});

This will find the first parent with class box then find the first child class with regex matching something and get the id.

$(".mylink").closest(".box").find('[class*="something"]').first().attr("id")