找到元素索引 [英] finding index of element

查看:61
本文介绍了找到元素索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的HTML:

<div class="TopClass">

  <div class="ContentClass">
    <div class="ActionClass">action</div>
  </div> 

  <div class="ContentClass">
    <div class="ActionClass">action</div>
  </div> 

  <div class="ContentClass">
    <div class="ActionClass">action</div>
  </div> 

</div>

我希望得到相对于TopClass的动作类的索引;如果用户点击第二个Action类,它应返回2.

I'm looking to get the index of the action class relative to TopClass; if the user clicks on the second Action class, it should return 2.

$('.ActionClass').click(function () {
    alert($(this).parent().parent().index());  // not working    
});


推荐答案

使用 .index 这样总是会给你的索引。 ActionClass 即使结构发生变化。但是当 .index 返回 0-based 索引时,我正在添加 1 输入它的输出:

Use .index like this which will always give you the index of .ActionClass even if the structure changes. But as .index returns 0-based index I am adding 1 into it's output:

$('.ActionClass').click(function () {
   alert($(this).closest('.TopClass').find('.ActionClass').index(this) + 1);
});​

工作小提琴

另一种较短的方式可能是这样的,它只适用于一个父 .TopClass 容器到目前为止但是如果使用的话可以小心使用你有不同的结构。上一个更安全,适用于一般情况

Another shorter way can be like this, it works fine with only one parent .TopClass container so far but use carefully if you have a different structure. Previous one is safer and works for general cases

$('.ActionClass').click(function () {
   alert($('.ActionClass').index(this) + 1);
});​

工作小提琴

这篇关于找到元素索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆