2016-06-28 49 views
0

我想獲取每個循環中的下一個索引值,如果索引是最後一個(這裏是2),則取第一個索引值。如何獲取jquery中的下一個索引值

所以我試了下面的代碼,但沒有工作。

keyword = 'on'; 
var nextitem = ''; 
$(".clsiteration").each(function(index, el) { 
    if ($(this).attr("src").toLowerCase().indexOf(keyword.toLowerCase()) > 0) { 
     if (index == 2) 
      nextitem = $(this).first().attr('data-val'); 
     else 
      nextitem = $(this).next().attr('data-val'); 
    } 
}); 

HTML

<div> 
     <img src="img_off.jpg" class="clsiteration" data-val="k1" > 
     <img src="img_on.jpg" class="clsiteration" data-val="k2" > 
     <img src="img_off.jpg" class="clsiteration" data-val="k3" > 
</div> 

我怎樣才能得到下一個索引值?謝謝

+0

$(本)。接下來()指數()https://api.jquery.com/index/ –

+0

@ToniMichelCaubet如果你看看其他部分是有笑: ) – guradio

+0

@guradio不,我沒有看到它.. –

回答

0

看看Snippet這是如何next()工作在JQUERY

$(function(){ 
 
keyword = 'k1'; 
 
var nextitem = ''; 
 
$(".clsiteration").each(function(index, el) { 
 
     if (index === 2){ 
 
      nextitem = $(this).closest("div").find("img:eq(0)").data('val'); 
 
      } 
 
     else { 
 
      nextitem = $(this).next().data('val'); 
 
      } 
 
    console.log(nextitem); 
 
}); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
 
<div> 
 
     <img src="img_off.jpg" class="clsiteration" data-val="k1" > 
 
     <img src="img_on.jpg" class="clsiteration" data-val="k2" > 
 
     <img src="img_off.jpg" class="clsiteration" data-val="k3" > 
 
</div>