簡體   English   中英

如何使用原始Javascript識別無序列表和/或嵌套列表序列中的上一個/下一個鏈接?

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

我正在努力解決這種情況。

使用vanilla Javascript,我需要確定前一個和下一個<a>元素,給定nn個深度為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>

Link 8的上一個是Link 7,下一個是Link 9。

Link 9的前一個是Link 8,下一個是Link 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];

(加上一些環繞邏輯)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM