简体   繁体   English

如何获得一个jQuery中某个元素远离某个元素的索引数?

[英]How to get number of index's a element is away from a certain element in jQuery?

Suppose I have the following HTML code: 假设我有以下HTML代码:

 // 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 ? 如您所见, perspectiveSlider__item是彼此的5个兄弟姐妹,并且每个兄弟姐妹都有一个唯一的类,现在我如何找到索引的.item-left-faded数量远离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() ? 我知道jQuery提供了next()prev()函数以及index()函数,但是有什么我可以创建的东西可以像ProvideMeTheIndexTheSelectedElementIsAwayFromTheTargetedElement()吗?

In the above case .item-left-faded is away from item-center by 2 index's , How do i achieve this functionality ? 在上述情况下, .item-left-fadeditem-center为2个索引,我如何实现此功能?

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? 请让我知道您的问题已解决?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM