【问题标题】:Jquery - using each() to get position of a class elementJquery - 使用 each() 获取类元素的位置
【发布时间】:2017-04-09 20:57:23
【问题描述】:

我需要知道“owl-item active”的位置,我知道当前位置是2。一共有3张照片。

<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”的位置?

我有这段代码,但找不到代码告诉我这个“owl-item active”在位置 2。

$('.owl-stage .owl-item').each(function( index, currentElement ) {
    console.log( index+1 );
    //console.log( $(currentElement).find('div.owl-item.active') ); 
});

有人可以告诉我如何做到这一点吗?

【问题讨论】:

    标签: javascript jquery each


    【解决方案1】:

    你需要使用hasClass方法:

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

    但是您可以通过将选择器传递给index 方法来更轻松地使用它:

    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>

    【讨论】:

      猜你喜欢
      • 2011-03-29
      • 1970-01-01
      • 1970-01-01
      • 2011-05-14
      • 1970-01-01
      • 1970-01-01
      • 2012-10-28
      • 2012-01-13
      • 2015-10-07
      相关资源
      最近更新 更多