jQuery - 获取元素的第二级父级

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2675317/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 14:01:26  来源:igfitidea点击:

jQuery - Getting the second level parent of an element

jqueryhtmlparent

提问by HandiworkNYC.com

I am trying to retrieve the parent of an <a> element's parent (grandparent?). I want to find that grandparent, then find a <b> tag in that element, then store that text as a variable to publish elsewhere on the page. I've been trying to use the parent() function but without success.

我正在尝试检索 <a> 元素的父元素(祖父母?)的父元素。我想找到那个祖父母,然后在该元素中找到一个 <b> 标记,然后将该文本存储为变量以在页面上的其他地方发布。我一直在尝试使用 parent() 函数,但没有成功。

Here's the code I tried:

这是我试过的代码:

    $('.mixPlayCell a').click( function() {
        var title = $(this).parent().get(0).parent().get(0).text();
        alert(title);
    });

采纳答案by MDCore

try:

尝试:

$(this).parent().parent().find('.thingtofind').text();

回答by Radek

For selecting a second parent

用于选择第二个父母

parents(':eq(1)')

looks smoother than

看起来比

parent().parent()

Also, you might find that

另外,你可能会发现

closest('ul')

fits the job better.

更适合这份工作。

回答by DidThis

parents()returns a list, so this works:

parent()返回一个列表,所以这有效:

$(this).parents()[1];

回答by Jeriko

$('.mixPlayCell a').click(function() {
  elem = $(this).parent().parent();
  title = $("tag selector goes here",elem).html();
});

Something like this?

像这样的东西?

回答by marcgg

There is only 1 parent, no need to .get(0)

只有 1 个父级,不需要 .get(0)

    var title = $(this).parent().parent().find("whateveryouwant").html();

回答by Jan Jongboom

$(this).parent().parent().find('mytag').text()

Should work just fine.

应该工作得很好。

You can use any selector in the findmethod. If you'll just need to search in the direct children of the grandparent's element, you can also use $.childreninstead of findwhich searches in all of the element's children.

您可以在find方法中使用任何选择器。如果您只需要在祖父元素的直接子元素$.childrenfind进行搜索,您还可以在所有元素的子元素中使用which代替which 搜索。

回答by ahmedkuzza

Try this for simple implementation :

试试这个简单的实现:

$('.mixPlayCell a').click( function() {
    var title = $(this).parents().text();
    alert(title);
});

Just changed .parent() with one .parents()

刚刚用一个 .parents() 改变了 .parent()

this is works for every jQuery versions.

这适用于每个 jQuery 版本。