Jquery索引与其他元素的关系

Jquery index in relation to other elements

本文关键字:关系 元素 其他 索引 Jquery      更新时间:2023-11-19

我想知道是否有可能找到一个元素相对于同一类元素数量的索引,如果有,我该怎么做?

所以,如果我有以下。。。

<div class="container">
    <p>This is content 1</p>
    <p>This is content 2</p>
    <p>This is content 3</p>
</div>
    ...other HTML
<div class="container">
    <p>This is content 1</p>
    <p>This is content 2</p>
    <p>This is content 3</p>
</div>

单击第一个容器中的项目,它将返回索引1,但如果单击第二个容器中一个项目,它会返回索引2,因为它是类为"container"的第二个div。

这可能吗?如果是这样的话,怎么做呢?

非常感谢您的帮助。

$(function() {
    $('.container p').on('click', function() {
      var index = $(this)   // point the clicked p
                      .parent()  // jump to .container parent
                      .index() +1;  // get index, As index() is zero based, so you can
                                    // add 1 to get 1,2,...
      alert( index );
    });
}):

你可以试试这个

$(document).ready(function(){
    $('div.container p').click(function(){
        alert($(this).parent().index());
    });
});​

实例