簡體   English   中英

Jquery - 使用each()獲取類元素的位置

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

我需要知道“貓頭鷹項目活躍”的位置,我知道目前的位置是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 active”的位置?

我有這段代碼,但找不到代碼的方法告訴我這個“貓頭鷹項目活躍”是在2號位置。

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

有人能給我一個如何做到這一點的線索嗎?

您需要使用hasClass方法:

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

但是通過將selector傳遞給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> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM