[英]Get index of div with class equal to active
I have a twitter bootstrap carousel with : 我有一个Twitter引导轮播:
<div id="myCarousel" class="carousel slide">
<div class="carousel-inner">
<div class="item">
<div id="container"></div>
</div>
<div class="item active">
<div id="container2"></div>
</div>
<div class="item">
<div id="container3"></div>
</div>
</div>
<!-- Controls -->
<a class="left carousel-control" href="#myCarousel" data-slide="prev">«</a>
<a class="right carousel-control" href="#myCarousel" data-slide="next">»</a>
</div>
Now when I click on, for ex. 现在,当我单击时,例如。 a button. 一个按钮。 I would like to have the index of the item with class = 'active'. 我想使用class ='active'获得该项目的索引。 In this example it would be the second div, so index = 1 (starts from 0). 在此示例中,它将是第二个div,因此index = 1(从0开始)。
To get the div with class = "active" I do this: 要获得class =“ active”的div,我可以这样做:
var activediv = $('.item').find('.active');
But when I want to find the index of the element like this: 但是当我想找到这样的元素的索引时:
var index = activediv.index();
I always get "-1" in my console, so he can't find the item ... But why? 我总是在控制台中收到“ -1”,所以他找不到该项目...但是为什么呢?
Does anyone knows what I'm doing wrong? 有人知道我在做什么错吗?
.index() is a function in the wrapper element. .index()是包装器元素中的一个函数。
Also active
is not a decedent of item
, it is a additional filter to the item
elements - so you need to use .filter()
instead of .find()
同时active
不是item
.filter()
item
,它是item
元素的附加过滤器-因此您需要使用.filter()
而不是.find()
var activediv = $('.item').filter('.active');//or $('.item.active')
var index = activediv.index();
You can always add data property to your targeted element. 您始终可以将data属性添加到目标元素。 Something like this. 这样的事情。
<div class="item active" data-something="1">
var index=$('.active').data('something');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.