父类中的 jquery 索引 [英] jquery index within a parent class
问题描述
我需要一种方法来找到一个子元素的索引号.
这是它的CSS
<div class="son"></div><div class="son"></div><div class="son"></div><div class="son"></div><div class="son"></div><div class="parent"><div class="son"></div><div class="son"></div><div class="son"></div><div class="son"></div><div class="son"></div>
我的jquery代码是这样的
var number = $(".son").index(this);
当我使用这段代码时,它会将儿子算作一个整体.例如,当我单击第二个父类中的第二个子元素时,它会给我一个 var 编号 7.我希望子类总是从零开始计数.
试试这个:
$(this).parent().find('.son').index(this)
正如其他成员提到的:
$(this).index()
完成工作,因为没有参数的 index() 返回元素相对于其兄弟元素的位置.
文档:
<块引用>如果没有参数传递给 .index() 方法,则返回值是一个整数,表示 jQuery 对象中第一个元素相对于其兄弟元素的位置.
I need a way to find the index number of one child element.
here is the CSS of it
<div class="parent">
<div class="son"></div>
<div class="son"></div>
<div class="son"></div>
<div class="son"></div>
<div class="son"></div>
</div>
<div class="parent">
<div class="son"></div>
<div class="son"></div>
<div class="son"></div>
<div class="son"></div>
<div class="son"></div>
</div>
My jquery code is like this
var number = $(".son").index(this);
When I use this code, it will count the son as a whole. Eg, when I click on the second child element in the second parent class, it will give me a var number 7. I want the son class always start counting from zero.
Try this:
$(this).parent().find('.son').index(this)
As other members mention:
$(this).index()
Does the job, since index() with no arguments returns position of element relative to its siblings.
Documentation:
If no argument is passed to the .index() method, the return value is an integer indicating the position of the first element within the jQuery object relative to its sibling elements.
这篇关于父类中的 jquery 索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!