I am trying to carry a class between li
's with combine each()
and eq()
methods when buttons clicked. I am using same code with previous and next buttons except i+1
and i-1
but it is returning me different problems.
Here is jsFiddle to examine.
html:
<span class="prev">prev</span>
<ul>
<li>0</li>
<li>1</li>
<li class="active">2</li>
<li>3</li>
<li>4</li>
</ul>
<span class="next">next</span>
jQuery:
var li = $('li');
$('.prev').click(function() {
li.each(function(i) {
if ( $(this).hasClass('active') ) {
console.log(i);
//this returning current true value = 2
li.removeClass('active');
li.eq(i-1).addClass('active');
//this is working better
//problem is: not selecting 4
}
});
});
$('.next').click(function() {
li.each(function(i) {
if ( $(this).hasClass('active') ) {
console.log(i);
//this returning current true value = 2
//problem starts:
//li.removeClass('active');
//when this is active; all active classes are gone
li.eq(i+1).addClass('active');
//try to select next 'li' here
//but it is selecting all li's bigger than current value
}
});
});
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…