У меня проблема с jQuery .next()
на моей ul
. То, что я хочу, когда пользователь нажимает на следующую кнопку, он только добавляет его в li
рядом с ним. По какой-то причине он продолжает добавлять его к каждому элементу списка. Вот рабочий пример:
$(document).ready(function(){
$('a.next').click(function(){
//alert('clicked');
$('ul.menu li').next().addClass('active');
});
});
Это потому, что $('ul.menu li')
выберет все ваши элементы списка в ul.menu
; .next()
затем найдет следующий элемент для каждого элемента в $('ul.menu li')
, и, следовательно, вы имеете дело с несколькими элементами при добавлении своего класса.
Я думаю, вы, вероятно, захотите начать с активного класса на одном из элементов li
, а затем использовать что-то вроде:
$('ul.menu li.active').removeClass('active').next().addClass('active');
Это потому, что ваш селектор слишком общий.
$('ul.menu li') //--> will return all li of the menu
.next() //--> will return all the next li to the selected li's
Вы можете вместо этого добавить активную к первой li
чтобы начать с и после щелчка следующего выбора next
с $('ul.menu li:active')
удалив текущий активный. И сделайте то же самое для предыдущего.
Вы можете сделать:
HTML:
<ul class="menu">
<li class="active">1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
</ul>
<a class="traverse" data-action="prev" href="#">previous</a>
<a class="traverse" data-action="next" href="#">next</a>
JS:
$(document).ready(function(){
var $menu = $('ul.menu'),
$menus = $menu.children('li');
$('a.traverse').click(function(){
var action = $(this).data('action'), //Get the action prev/next
jump = (action === 'next' ? 'first' : 'last'), //based on action determine the jump to switch to first or last when reached the end to enable a cycle
$active = $menus.filter('.active').removeClass('active'), //remove current active li class
$target = $active[action](); //get the target applying the action
if ( $target.length === 0){ //If no target i.e when it is at first or last and clicking on prev or next reptly
$target = $menus[jump](); //get the next element using the jump
}
$target.addClass('active'); //add class to the target
});
});
Вам нужно отслеживать следующий элемент
var currentLi = $('.menu li').first();
$('a.next').click(function(){
if(!currentLi.hasClass('active')) {
currentLi.addClass('active');
} else {
currentLi.removeClass('active');
currentLi = currentLi.next();
currentLi.addClass('active');
}
});
Я разветкил ваш jsfiddle http://jsfiddle.net/hatemalimam/8nqxt/