jQuery:获取父代,父代ID?


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

如何使用jQuery获取ul(myList)的ID?单击链接时触发我的j脚本事件。我努力了:

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

但是它得到了li的ID,我需要再高一点,而且我也无法将点击附加到li。

Answers:


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

是如何获取父母的父母的ID。

编辑:

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

是针对您的案例的更简单的解决方案。


1
打电话给父母。两次都不是有效的,也不是未来的证明
gotofritz

2
parent().parent()绝对比parents('ul')后者快,因为后者将一直搜索<html>标记以查找<ul>标记并返回所有标记。closest('ul')是个不错的选择,因为它会在第一次出现后停止搜索,但是最接近的元素还包括正在调用的元素。$(this).parent().closest('ul')除非是$(this)将永远不是<ul> ,否则也许是最好的选择。
Casey Foster 2012年

同意“最接近”是理想的方法。最初并没有意识到,但是任何选择器都可以代替'ul'。
HoldOffHunger '16


0

这是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>

让我知道这是否有帮助。

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.