Ho un elenco di elementi che voglio attraversare da qualsiasi punto in qualsiasi direzione. Voglio anche aggirare l'elenco, cioè se finisco sull'ultimo elemento dell'elenco e clicco su Avanti, voglio che il prossimo elemento sia il primo elemento dell'elenco. La mia pagina è semplice, solo una lista non ordinata di 5 elementi, 2 pulsanti (uno per il precedente e uno per il successivo) e una textarea che visualizza i risultati. Qui è il mio codice:Attraversare un elenco con 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>
Come si siede, quando scatto sopra o avvicino l'ultima voce, premendo il pulsante accanto cancella la textarea e rende entrambi i pulsanti non rispondono. Logicamente, so che ci deve essere una dichiarazione if se si afferma che l'elemento corrente è l'ultimo elemento, quindi l'elemento successivo deve essere il primo elemento. Non riuscivo a capire come codificarlo. Ecco l'jsfiddle: