点击JQuery/HTML5显示元素的索引/位置

show index/position of element on click JQuery/HTML5

本文关键字:索引 元素 位置 显示 JQuery HTML5 点击      更新时间:2023-11-19

我在一个具有相同类名(按钮)的页面上调用了许多操作,如下所示:

<div class="topClass">
    <div class="classNameone">
        <p>bit of schpiel about section 1</p>
        <a href="#" class="Button">click me!</a>
    </div>
    <div class="classNametwo">
        <p>bit of schpiel about section 2</p>
        <a href="#" class="Button">click me!</a>
    </div>
</div>

我想让jQuery告诉我,当我点击它时,我正在点击哪个链接,而不必添加另一个类或ID。

例如,1用于第一个按钮,2用于第二个按钮(或者0和1取决于索引开始)。

我试着在点击元素时使用以下内容:

$(this).parent().parent().find('.Button').index(this)

但所有返回的都是-1。

如有任何帮助,我们将不胜感激。

以下代码将在具有类topClassdiv的透视图中返回单击的anchor元素的index

试试这个,

$('a').click(function(){    
    alert($(this).closest('div').index() +1 );
});

演示

参考:.Closest()