我试图在单击按钮时在li
's 和 combineeach()
和方法之间携带一个类。eq()
我对上一个和下一个按钮使用相同的代码,i+1
但i-1
它返回给我不同的问题。
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
}
});
});