Mam listę przedmiotów, które chcę przejść z dowolnego punktu w dowolnym kierunku. Chciałbym również pętli wokół listy, co oznacza, że jeśli trafię na ostatni element listy i kliknij na następny, chcę, aby następny element był pierwszym elementem na liście. Moja strona jest prosta, zawiera tylko nieuporządkowaną listę 5 elementów, 2 przyciski (jeden dla poprzedniego i jeden dla następnego) oraz obszar tekstowy wyświetlający wyniki. Tu jest mój kodu:Przechodzenie do listy z jQuery
$(function() {
var prev = $("#prev"); // grabbing the prev button
var next = $("#next"); // grabbing the next button
var listItems = $("#listItems p"); // grabbing the p elements of the list items
var results = $("#results"); // grabbing the textarea
var itemText; // variable for holding the text node
var selectedItem; // variable for the current selected item
listItems.click(function() { // click event for any item
itemText = $(this).text(); // selects the text of the clicked list item
results.text(itemText); // adds text to textarea
selectedItem = $(this).parent(); // sets selected item as the li element of the selected p element
});
next.click(function() { // click event for next button
var nextItem = selectedItem.next(); // setting the next item
itemText = nextItem.children("p").text(); // grabbing the text of the next item
results.text(itemText); // adds text to textarea
selectedItem = nextItem; // sets next item
});
prev.click(function() { // click event for the prev button
var prevItem = selectedItem.prev(); // setting the prev item
itemText = prevItem.children("p").text(); // grabbing the text of the prev item
results.text(itemText); // adds text to textarea
selectedItem = prevItem; // sets prev item
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<ul id="listItems">
<li><p>First item</p></li>
<li><p>Item 2</p></li>
<li><p>Item 3</p></li>
<li><p>Item 4</p></li>
<li><p>Last item</p></li>
</ul>
<button id="prev">Prev</button>
<textarea name="results" id="results" cols="30" rows="1"></textarea>
<button id="next">Next</button>
Jak się siedzi, gdy kliknę lub zbliżyć się do ostatniego elementu, naciskając przycisk Dalej czyści textarea i czyni oba przyciski odpowiadać. Logicznie, wiem, że musi istnieć instrukcja if stwierdzająca, czy bieżący element jest ostatnim elementem, to następny element musi być pierwszym elementem. Po prostu nie mogłem wymyślić, jak to zakodować. Oto jsfiddle: