jQuery:获取父级,父级 ID?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10260667/
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 09:02:35  来源:igfitidea点击:

jQuery: get parent, parent id?

jquery

提问by panthro

<ul id ="myList">
<li><a href="www.example.com">link</a></li>
</ul>

How can I get the id of the ul (myList) using jQuery? My j-script event is triggered when the a link is clicked. I have tried:

如何使用 jQuery 获取 ul (myList) 的 id?单击链接时会触发我的 j-script 事件。我试过了:

$(this).parent().attr('id');

But it gets the id of the li, I need to go one higher, and I cant attach the click to the li either.

但是它获取了 li 的 id,我需要再高一个,而且我也无法将点击附加到 li 上。

回答by Casey Foster

$(this).parent().parent().attr('id');

Is how you would get the id of the parent's parent.

是如何获得父母的父母的 id。

EDIT:

编辑:

$(this).closest('ul').attr('id');

Is a more foolproof solution for your case.

是针对您的情况的更万无一失的解决方案。

回答by abhijit

 $(this).closest('ul').attr('id');

回答by Juraj Guni?

Here are 3 examples:

这里有3个例子:

$(document).on('click', 'ul li a', function (e) {
    e.preventDefault();

    var example1 = $(this).parents('ul:first').attr('id');
    $('#results').append('<p>Result from example 1: <strong>' + example1 + '</strong></p>');

    var example2 = $(this).parents('ul:eq(0)').attr('id');
    $('#results').append('<p>Result from example 2: <strong>' + example2 + '</strong></p>');
  
    var example3 = $(this).closest('ul').attr('id');
    $('#results').append('<p>Result from example 3: <strong>' + example3 + '</strong></p>');
  
  
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ul id ="myList">
  <li><a href="www.example.com">Click here</a></li>
</ul>

<div id="results">
  <h1>Results:</h1>
</div>

Let me know whether it was helpful.

让我知道它是否有帮助。