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

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

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

但是它得到了li的id,我需要再高一点,我也不能将点击附加到li。

4

3 回答 3

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

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

编辑:

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

对于您的情况来说,这是一个更简单的解决方案。

于 2012-04-21T16:07:14.533 回答
13
 $(this).closest('ul').attr('id');
于 2012-04-21T16:10:21.847 回答
1

这里有 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>

让我知道它是否有帮助。

于 2016-09-08T10:15:12.163 回答