父级的 jQuery 父级

我当前正在尝试寻找一个元素的父元素的父元素。我有一个链接被点击,是在一个 <td>,我想得到的 <tr>对象。

为什么“ $(this) . father () . father ()”不起作用? 什么会起作用?

谢谢,
布兰登

编辑: 似乎是我的语法中的一个错误把整个事情搞砸了。“ $(this)。家长()。的确有效,但我最终选择了 $(this)。因为它似乎是最有效的解决方案。

104039 次浏览

This snippet has performed for me in the past:

$(this).parent().parent();

Post some code for us to see if there might be another problem somewhere...

It should work. You can also try $(this).parents(tag) , where tag is the tag you want to find.

For example:

$(this).parents("tr:first")

Will find the closest tr "up the chain".

Try wrapping the $(this).parent() into an jQuery object like $($(this).parent()) I often find the need to do this to make sure I have a valid jquery object. From there you should be able to get a hold of the parents parent, or using the prev() perhaps.

That should work... you might try

$(this).parents(':eq(1)');

The .parents(selector) says get all ancestors that match the selector

and the :eq(1) says find the oneth (zero-indexed, so the second) element in the list

The best way would probably be using closest:

$(this).closest('tr');

Check out the documentation:

Closest works by first looking at the current element to see if it matches the specified expression, if so it just returns the element itself. If it doesn't match then it will continue to traverse up the document, parent by parent, until an element is found that matches the specified expression. If no matching element is found then none will be returned.

also try

$(this).closest('div.classname').hide();
var getParentNode = function(elem, level) {
level = level || 1;
for (var i = 0; i < level; i++) {
if (elem != null) {
elem = elem.parentNode;
}
}
return elem;
}

.closest() is not always best option specially when you have same element construct.

<div>
<div>
<div>
</div>
</div>
</div>

You can do parent of a parent and it's very easy:

var parent = $('.myDiv').parent();
var parentParent = $(parent).parent();
var parentParentParent = $(parentParent).parent();

etc.

If you have any sort of id/class for the parent, you can use parents() but that will give you all parents up to the < body > unless you filter() or stop it some other way like

$(this).parents('.myClass');

Hope this helps someone :)