<ul id ="myList">
<li><a href="www.example.com">link</a></li>
</ul>如何使用jQuery获取ul (myList)的id?我的j-script事件在单击a链接时触发。我试过了:
$(this).parent().attr('id');但是它得到了li的id,我需要更高一点,而且我也不能把click附加到li上。
发布于 2012-04-22 00:07:15
$(this).parent().parent().attr('id');是如何获取父对象父对象的id的。
编辑:
$(this).closest('ul').attr('id');对你的情况来说是一个更可靠的解决方案。
发布于 2012-04-22 00:10:22
$(this).closest('ul').attr('id');发布于 2016-09-08 18:15:12
这里有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>
让我知道它是否有帮助。
https://stackoverflow.com/questions/10260667
复制相似问题