我有一个项列表,想要从任意点以任何方向遍历它。我还想循环遍历该列表,这意味着如果我在最后一个列表项上并点击下一个,我希望下一个项是列表中的第一个项。我的页面很简单,只是一个包含5个项目、2个按钮(一个用于上一个,一个用于下一个)和显示结果的文本区域的无序列表。以下是我的代码:
$(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>