jQuery:next()和prev()有一个包装器吗?

mat*_*att 1 html keyboard jquery

我有以下html:

<article class="layer" id="one"> </article>
<article class="layer" id="two"> </article>
<article class="layer" id="three"> </article>

<section class="cat" id="something">    
    <article class="layer" id="four"> </article>
    <article class="layer" id="five"> </article>
</section>

<article class="layer" id="six"> </article>
…
Run Code Online (Sandbox Code Playgroud)

我想通过所有文章用我的键盘导航.像这样......

var view,
        next,
        prev;

    $(document).keydown(function(e) {

        view = $('.layer:in-viewport');
        next = view.next().attr('id');
        prev = view.prev().attr('id');

        switch (e.keyCode) {
            case 38: // Up
                if ( prev != undefined )
                    scroll($("#"+prev), true, 0);
                break;
            case 40: // Down
                if ( next != undefined )
                    scroll($("#"+next), true, 0);
                break;
        }

    });
Run Code Online (Sandbox Code Playgroud)

如果所有文章都在同一个容器中,这将正常工作.但是,正如您在上面所看到的,我还有一些部分包含这些文章.我只是想让它工作好像没有这样的部分并article#three直接跳转article#four

知道如何才能做到这一点吗?

编辑:

导致Firefox中的错误的事情......

if ( top.location.hash ) {
        hash = top.location.hash.substring(3);
        catHash = hash.split('/')[1];

        if ( catHash !== undefined )
            scroll($("#"+catHash), false, 0);
        else
            scroll($("#"+hash), false, 0);

        if ( hash != "index" && !isiPhone() )
            $('#top').slideDown();  
    }
Run Code Online (Sandbox Code Playgroud)

只有那4行导致错误...

if ( catHash !== undefined )
    scroll($("#"+catHash), false, 0);
else
    scroll($("#"+hash), false, 0);
Run Code Online (Sandbox Code Playgroud)

如果当前top.location中存在哈希,则这几行仅检查页面加载.因此,如果网址看起来像这样,www.something.com/#!/category/idOfElement我想跳转到页面上的该位置.

为什么这4行只会在firefox中导致这个bug?

Rob*_*b W 8

选择"真正的"下一个<article>元素的最简单方法是使用.index.eq方法.

var allArticles = $("article.layer");
var index = allArticles.index(view);   // Zero-based indexes. Not found = -1
var prev = index <= 0 ? $() : allArticles.eq(index-1);
var next = allArticles.eq(index + 1); 
Run Code Online (Sandbox Code Playgroud)