【问题标题】:Jquery index in relation to other elements相对于其他元素的 Jquery 索引
【发布时间】:2012-07-18 14:28:32
【问题描述】:

我想知道是否可以找到与具有相同类的元素数量相关的元素索引,如果可以,我将如何去做?

所以如果我有以下...

<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,因为它是具有“容器”类的第二个 div。

这可能吗?如果是这样,怎么办?

非常感谢您的帮助。

【问题讨论】:

  • $(this).parent().index() 应该可以工作...如果您想要 1 和 2 而不是 0 和 1,请添加 +1。

标签: javascript jquery indexing


【解决方案1】:
$(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 );
    });
}):

【讨论】:

    【解决方案2】:

    你可以这样试试

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

    live example

    【讨论】:

      猜你喜欢
      • 2013-09-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多