某个类的元素的jquery索引 [英] jquery index of element of a certain class

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

问题描述

我在一个容器中有几个特定类的元素,我想获取该特定元素的索引.假设我有这个HTML:

I have several elements of a certain class within a container and I want to get the index of that particular element. Suppose I have this HTML:

<div id="TheContainer">

  <div class="MyClass">My Class</div>
  <div class="SomeClass">Not My Class</div>
  <div class="SomeOtherClass">Not My Class</div>
  <div class="SomeClass">Not My Class</div>
  <div class="MyClass">My Class</div>
  <div class="SomeOtherClass">Not My Class</div>
  <div class="SomeClass">Not My Class</div>
  <div class="MyClass">My Class</div>

</div>

我想获取MyClass的索引.这是我尝试过的:

I want to get the index of MyClass. This is what I tried:

$('#TheContainer').on({
    click: function () { 

       console.log($(this).parent().children('.MyClass').index()); }

}, '.MyClass');

例如,如果用户单击第三个MyClass元素,则应在控制台2上运行. jsFiddle是这里.

So for instance, if the user clicks on the third MyClass element, it should console 2. The jsFiddle is here.

谢谢.

推荐答案

请注意, index() 有一个可选的元素争论:

Note that index() has an optional element arguement:

.index( element )

元素

类型:Element或jQuery DOM元素或 要查找的jQuery对象.

Type: Element or jQuery The DOM element or first element within the jQuery object to look for.

因此,在这种情况下,您可以使用this作为该参数:

So, in this case you could jusr use this as that argument:

$(this).parent().children('.MyClass').index(this));

jsFiddle此处.

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

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