Suppose I have the following HTML code:
// post the jquery code here...
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div class="perspectiveSlider__main"> <div class="perspectiveSlider__slidesContainer"> <div class="perspectiveSlider__item item-left-faded"> <img src="img/slide-1.jpg" alt=""> </div> <div class="perspectiveSlider__item item-left"> <img src="img/slide-2.png" alt=""> </div> <div class="perspectiveSlider__item item-center"> <img src="img/slide-3.png" alt=""> </div> <div class="perspectiveSlider__item item-right"> <img src="img/slide-5.jpg" alt=""> </div> <div class="perspectiveSlider__item item-right-faded"> <img src="img/slide-6.jpg" alt=""> </div> </div> </div>
As you can see perspectiveSlider__item
are 5 siblings of each other and each also has a unique class, now how do I find the number of index's .item-left-faded
is away from item-center
?
I know jQuery provides a next()
and prev()
functions and also index()
function but is there something that I can create that will work like a ProvideMeTheIndexTheSelectedElementIsAwayFromTheTargetedElement()
?
In the above case .item-left-faded
is away from item-center
by 2 index's , How do i achieve this functionality ?
console.log($('.item-right-faded').index()-$('.item-center').index());
阅读文档:-https: //api.jquery.com/index/
Store your elements to an array with index and find your required classes and subtract indexes between them
here are code snippet to perform my thought
$(document).ready(function(){
var allItems = [];
$('.perspectiveSlider__item').each(function(){
allItems.push({ index: $(this).index(), className:$(this).attr('class').replace('perspectiveSlider__item ','') })
})
function ProvideMeTheIndexTheSelectedElementIsAwayFromTheTargetedElement(fromClass,toClass){
var fromIndex = allItems.filter(function(item){
if(item.className == fromClass){
return item.index;
}
});
var toIndex = allItems.filter(function(item){
if(item.className == toClass){
return item.index;
}
});
return fromIndex[0].index - toIndex[0].index;
}
console.log(ProvideMeTheIndexTheSelectedElementIsAwayFromTheTargetedElement('item-left-faded','item-center'));
})
Please let me know your issue is solve?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.