Jquery - using each() to get position of a class element

自闭症网瘾萝莉.ら 提交于 2020-01-03 17:16:26

问题


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>

How can I get the position of this "owl-item active" using a Jquery .each() ?

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?


回答1:


You need to use hasClass method:

$('.owl-stage .owl-item').each(function( index, currentElement ) {
   if( $( this ).hasClass( 'active' ) ) { 
     console.log( index+1 );
   }
});

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>


来源:https://stackoverflow.com/questions/40805301/jquery-using-each-to-get-position-of-a-class-element

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!