如何使用vanilla Javascript识别无序和/或嵌套列表序列中的上一个/下一个链接

How can I identify the previous/next link in a sequence of unordered and/or nested lists using vanilla Javascript?

本文关键字:链接 下一个 上一个 列表 Javascript vanilla 何使用 识别 无序 嵌套      更新时间:2023-09-26

我正试图了解这个场景。

使用香草Javascript,我需要识别上一个和下一个<a>元素,给定n中的任何给定链接-n深度的无序列表的数量。

下面是我的意思的一个示例结构:

<ul>
    <li><a href="http://www.example.com/">Link 1</a></li>
    <li><a href="http://www.example.com/">Link 2</a></li>
    <li><a href="http://www.example.com/">Link 3</a></li>
</ul>
<ul>
    <li><a href="http://www.example.com/">Link 4</a></li>
    <li><a href="http://www.example.com/">Link 5</a>
    <ul>
        <li><a href="http://www.example.com/">Link 6</a></li>
        <li><a href="http://www.example.com/">Link 7</a></li>
    </ul></li>
    <li><a href="http://www.example.com/">Link 8</a></li>
</ul>
<ul>
    <li><a href="http://www.example.com/">Link 9</a></li>
</ul>

链接8的上一个链接是链接7,下一个是链接9。

链接9的上一个链接是链接8,下一个是链接1。

等等。

在结构的一个层面上,我能够用这样的东西来解决这个问题:

function linkNext(currentFocus) {
    currentFocus = currentFocus || document.activeElement;
    var theNextElement;
    if (currentFocus.parentNode.nextElementSibling === null) { // Last <li> in list.
        if (currentFocus.parentNode.parentNode.nextElementSibling === null) { // Last list in bar.
            theNextElement = window.barbarbar.querySelector('a');
        } else {
            theNextElement = currentFocus.parentNode.parentNode.nextElementSibling.querySelector('a');
        }
    } else {
        theNextElement = currentFocus.parentNode.nextElementSibling.querySelector('a');
    }
    return theNextElement;
}
function linkPrev(currentFocus) {
    currentFocus = currentFocus || document.activeElement;
    var thePrevElement;
    if (currentFocus.parentNode.previousElementSibling === null) { // First <li> in list.
        if (currentFocus.parentNode.parentNode.previousElementSibling === null) { // First list in bar.
            thePrevElement = window.barbarbar.querySelector('a:last-of-type');
        } else {
            thePrevElement = currentFocus.parentNode.parentNode.previousElementSibling.querySelector('li:last-of-type a');
        }
    } else {
        thePrevElement = currentFocus.parentNode.previousElementSibling.querySelector('a');
    }
    return thePrevElement;
}

但这已经超出了单一的深度,我很难理解潜在的解决方案。即使我使用的是jQuery(我不是),即使是像.closest().parents()这样的东西似乎也不太适合。

有没有更好的方法呢?我真的需要在这里遍历树吗?

在我看来,你只需要保留一个所有链接的列表,并找到当前链接的位置:

var links = Array.prototype.slice.call(document.querySelectorAll('a'));
var index = links.indexOf(currentFocus);
// nextLink = links[index - 1];
// previousLink = links[index + 1];

(加上一些环绕的逻辑)