使用jQuery获取列表中的下一个或上一个项目

时间:2013-03-12 10:26:24

标签: jquery html

我正在处理一个页面,该页面具有基于索引的下一个和上一个链接。

我开始做这样的事情:

var nextPage = $("a.selected").next().find('a').attr('href');
window.location = nextPage;
return true;

问题是,如果选择'这不起作用。锚没有孩子或更多的兄弟姐妹。我希望能够转到父级别的下一个直接链接,并继续通过树继续。在示例标记上,我希望能够从" Last Item"到"测试"并且如果有孩子的话,去测试孩子......

从我所看到的,我需要为每个看似不可靠的关卡创造条件。最好的方法是什么?

标记看起来像http://jsfiddle.net/wQy6Q/

感谢。

3 个答案:

答案 0 :(得分:1)

如果您可以更改标记,则可以使用“data”属性来检索下一个锚点。

标记示例:

<ul>
    <li><a href="test" data-index="1">Test 1</a></li>
    <li><a href="test" data-index="2">Test 2</a></li>
<ul>

Javascript示例:

var index = $("a.selected").attr('data-index');
var nextPage = $('a[data-index="' + (index + 1) + '"]').attr('href');
window.location = nextPage;
return true;

如果您不想使用属性,也可以使用css类。

答案 1 :(得分:1)

IF 我理解您的要求:

对于您的示例:按以下顺序遍历树链接:

  • 1st:数据概述
  • 第二部分:数据部分如何协同工作
  • 3rd:数据示例软件
  • 第4期:上传期间数据如何使用您的Internet连接
  • 5th:Data Stash
  • 6th:Web访问数据
  • 7th:Data Mobile App
  • 8th:数据要求
  • 9th:Data Security

等......

然后

$('a').each(function(index, link) {
    console.log(index);
    console.log(link);
    $(link).attr('href'); // href attribute
});

(见小提琴:http://jsfiddle.net/wQy6Q/13/

如果不让我知道,我将删除此答案

评论后(您可以跳过变量以获得更简单的代码):

var collection = $('.treeview a');
var needle = $('.treeview a.selected');
var index = collection.index(needle);

if (index !== -1) { // we have a selected link
    var resultLink = $('.treeview a:eq(' + (index + 1) + ')');
    if (resultLink) { // not the last link
        console.log(resultLink.attr('href'));
    } else { // if last link we retrieve the first one (remove this if you don't need this)
        $('.treeview a:first').attr('href');
    }

}

示例小提琴:http://jsfiddle.net/wQy6Q/19/(重要提示:出于测试原因,我将所选链接移动到小提琴中的第二个)。

答案 2 :(得分:1)

试试这个

var selected = $("a.selected");

//find children
var next = selected.find('a:first');

//find next
if(!next.length){
    next = selected.next().find('a:first');
}

//find parent
var parent = selected.parent();
while(!next.length && parent.not('.treeview')){
    var els = parent.find('a');
    var index = els.index(selected);
    console.log(next, parent)
    next = els.filter(':gt(' + index + ')').first();
    parent = parent.parent();
}

if(next.length){
    console.log(next);
    selected.removeClass('selected');
    next.addClass('selected')
}else{
    console.log('finished')
}

演示:Fiddle

相关问题