这是我的标记:
<div>
<h2><a href="link-here">Link Text</a></h2>
<p>Description</p>
<h2><a href="link-here">Link Text</a></h2>
<p>Description</p>
<h2><a href="link-here">Link Text</a></h2>
<p>Description</p>
.. Unknown number of such elements...
</div>
当用户单击链接时,我想获取其索引。我尝试使用 $(this).index();
但它返回零。如何获取链接?
最佳答案
这会起作用:
$(document).ready(function(){
$('a').on('click',function(){
alert($('a').index($(this)));
});
});
在 jQuery 文档 ( https://api.jquery.com/index/ ) 中,我们读到:
If .index() is called on a collection of elements and a DOM element or jQuery object is passed in, .index() returns an integer indicating the position of the passed element relative to the original collection.
关于javascript - 如何在 jQuery 中获取点击链接的索引?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35245885/