Jquery - 使用each()获取类元素的位置 [英] Jquery - using each() to get position of a class element
本文介绍了Jquery - 使用each()获取类元素的位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要知道猫头鹰项目有效的位置,我知道目前的位置是2.总共有3张照片。
I need to know the position of the "owl-item active", I know that the current position is 2. There are 3 photos in total.
<div style="transform: translate3d(-825px, 0px, 0px); transition: all 0.25s ease 0s; width: 48675px;" class="owl-stage">
<div style="width: 825px; margin-right: 0px;" class="owl-item">
<div class="gallery-item" style="background-image: url('/image/144/1.jpg');"></div>
</div>
<div style="width: 825px; margin-right: 0px;" class="owl-item active">
<div class="gallery-item" style="background-image: url('/image/144/2.jpg');"></div>
</div>
<div style="width: 825px; margin-right: 0px;" class="owl-item">
<div class="gallery-item" style="background-image: url('/image/144/3.jpg');"></div>
</div>
</div>
如何使用Jquery .each()获取此owl-item active的位置?
How can I get the position of this "owl-item active" using a Jquery .each() ?
我有这段代码,但无法找到代码的方法告诉我这个owl-item active位于第2位。
I've this code, but can't find a way to the code tell me that this "owl-item active" is in the position 2.
$('.owl-stage .owl-item').each(function( index, currentElement ) {
console.log( index+1 );
//console.log( $(currentElement).find('div.owl-item.active') );
});
有人能给我一些关于如何做到这一点的线索吗?
Can someone give me a clue on how to do this?
推荐答案
您需要使用 hasClass
方法:
You need to use hasClass
method:
$('.owl-stage .owl-item').each(function( index, currentElement ) {
if( $( this ).hasClass( 'active' ) ) {
console.log( index+1 );
}
});
但只需将选择器传递给 index
方法:
But you can use it even easier by just passing selector to index
method:
console.log( $('.owl-stage .active').index( '.owl-item' ) + 1 );
$(function() {
console.log( '.active index is', $('.owl-stage .active').index( '.owl-item' ) + 1 );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div style="transform: translate3d(-825px, 0px, 0px); transition: all 0.25s ease 0s; width: 48675px;" class="owl-stage">
<div style="width: 825px; margin-right: 0px;" class="owl-item">
<div class="gallery-item" style="background-image: url('/image/144/1.jpg');"></div>
</div>
<div style="width: 825px; margin-right: 0px;" class="owl-item active">
<div class="gallery-item" style="background-image: url('/image/144/2.jpg');"></div>
</div>
<div style="width: 825px; margin-right: 0px;" class="owl-item">
<div class="gallery-item" style="background-image: url('/image/144/3.jpg');"></div>
</div>
</div>
这篇关于Jquery - 使用each()获取类元素的位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文