<ul id ="myList">
<li><a href="www.example.com">link</a></li>
</ul>
我如何使用jQuery获取ul(myList)的id?当点击a链接时,我的j-script事件被触发。 我已经尝试过:
$(this).parent().attr('id');
但是它获取的是li的id,我需要再高一级,并且我也不能将点击事件附加到li上。
<ul id ="myList">
<li><a href="www.example.com">link</a></li>
</ul>
我如何使用jQuery获取ul(myList)的id?当点击a链接时,我的j-script事件被触发。 我已经尝试过:
$(this).parent().attr('id');
但是它获取的是li的id,我需要再高一级,并且我也不能将点击事件附加到li上。
$(this).parent().parent().attr('id');
如何获取父元素的父元素 ID。
编辑:
$(this).closest('ul').attr('id');
这是一个更加稳妥的解决方案。
parent().parent()
明显比 parents('ul')
更快,因为后者会一直向上搜索到 <html> 标签以寻找 <ul> 标签并返回所有结果。closest('ul')
是一个不错的选择,因为它在找到第一个匹配项后就停止搜索,但 closest 还包括被调用元素本身。也许 $(this).parent().closest('ul')
是最好的选择,除非 $(this)
永远不是 <ul>。 - Casey Foster $(this).closest('ul').attr('id');
以下是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>
请告诉我这是否有帮助。