javascript - 如何在 jQuery 中获取点击链接的索引?

标签 javascript jquery

这是我的标记:

<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/

相关文章:

javascript - jQuery.isPlainObject() 和 jQuery.isEmptyObject() 之间的区别

jquery - 向scrollTo插件添加事件以滚动键盘导航

javascript - 如何验证动态添加的输入字段

javascript - 试图将 zlib deflate 包装成异步等待

javascript - 检测何时触摸另一个 View - 在 React Native 中使用 PanResponder 拖动

javascript - 为什么调用 $.getScript 而不是直接使用 &lt;script&gt; 标签?

jQuery 函数、setInterval 或创建的函数,不起作用

javascript - jqGrid 中的动态列和使用下拉列表

javascript - 带有文本形式替代的 Bootstrap 子菜单?

java - 监控应用程序运行状况以及用户使用 JavaScript 执行的操作