我正在尝试在列表中实现一些下一个/上一个导航,因为页面设计我不得不分成两个列表。我可以使用jQuery在单个列表中轻松完成此操作,但无法弄清楚如何从第一个列表中的最后一项跳转到第二个列表中的第一个项目(反之亦然)。代码在这里:http://pastebin.com/5DjtzGBa
答案 0 :(得分:1)
您可以检查这是否是最后一个li,然后跳转到下一个列表。类似于跳转到prev的逻辑:
伪代码(我稍后会尝试发布一个工作函数)
$("#nav ul li a").bind("click keypress",function(e){
var dTitle=$(this).text();
var dContentkey=$(this).attr("id");
if($(this).parent().is(":last")) {
// get next ul item
}
else {
nextItem=$(this).parent().next("li").find("a").attr("id");
}
testItem=$(this).parent("#nav").next("div ul li").find("a").attr("id");
e.preventDefault();
$("#currTitle").text("Clicked item: "+dTitle);
$("#nextObjID").text("Next Item: "+nextItem);
$("#testObjID").text("Test Item: "+testItem);
});
答案 1 :(得分:1)
你想要(作为替代,如果你在当前列表中的第一次搜索没有返回结果):
nextItem = $(this)
.closest("div") // find the closest div ancestor
.next("div") // then its next sibling div
.find("ul li a")// then the first link in the list
.attr("id");
答案 2 :(得分:1)
首先,如果您要对ID进行编号,就像在您的示例中一样,只需使用ID属性查找下一个或上一个项目。
其次,这是一个更通用的解决方案。这将适用于您的情况,但如果您在随机位置中有LI,div或遍布页面的任何内容,它也会起作用,并且您希望将所有单个元素链接在一起,以便您可以向前和向后遍历它们。
$("#nav li")
.eq()
中的选择即可。在你的情况下。Working example(点击LI查看下一个是哪一个)
$(function() {
// You can link lists anywhere on the page,
// not just consecutive ones
// create an object of all lis and store the index
// Let's cache our big combine list
$bigList = $("ul.big-list li");
// Store the index value in the list item
$bigList.each(function(index) {
$(this).data("indexNum", index);
});
// Retrieve stored index value and add or subtract one
$bigList.click(function() {
// Add one to find next
// Subtract one to find prev
var nextIndex = $(this).data("indexNum") + 1;
// Wrap from last to first
if (nextIndex === $bigList.length)
nextIndex = 0;
// Find next or prev using .eq()
$bigList.eq(nextIndex).animate(
{"font-size":"200%"},500).animate(
{"font-size":"100%"},500);
});
});