我正在尝试理解这个场景。
使用普通 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];
(加上一些环绕逻辑)
关于javascript - 如何使用普通 Javascript 识别一系列无序列表和/或嵌套列表中的上一个/下一个链接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34644362/