[英]How to position each element with a class identifier differently using jQuery?
[英]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.