识别并跳转到文档上的最后一个锚点


function goToPrevAnchor() {
var anchors = document.anchors;
var loc = window.location.href.replace(/#.*/,'');
var prevAnchorName;
 // Get name of the current anchor from the hash
var anchorName = window.location.hash.replace(/#/,'');
if (anchorName) {
// Find current element in anchor list, then
// go back to prev anchor name, or if at last anchor, set to first
for (var i=0, iLen=anchors.length; i<iLen; i++) {
  if (anchors[i].name == anchorName) {
    prevAnchorName = anchors[--i % iLen].name;
    break;
  }
 }
}
// If there was no anchorName or no match,
// set prevAnchorName to last anchor name
if (!prevAnchorName) {
prevAnchorName = anchors[(anchors.length - 1)].name; //this is the issue
}
// Go to new URL
window.location.href = loc + '#' + prevAnchorName;
}

我从另一个堆栈溢出问题中得到了这部分,锚点[(anchors.length - 1(]。如何获取网站的最后一个锚元素

这是 html

<li><a href="#1">Go to 1</a></li>
<li><a href="#2">Go to 2</a></li>
<li><a href="#3">Go to 3</a></li>
<button id="prev_btn" class="fixed" onclick="goToPrevAnchor()">Prev</button>

(是的,我知道我需要将 onClick 更改为函数。

理解我破解/组装在一起的脚本的方式是,如果url哈希在最开始并且单击按钮,url哈希将指向最后一个锚标签的末尾;至少这是我的意图。

我真的无法理解为什么它不起作用,因为我的原版JavaScript知识非常有限。

请不要告诉我回到jQuery。 这实际上是我正在构建的UI的最后一部分,在此之后,我完全完成了。 我不想回去加载jQuery只是为了这一行代码,我无法让它工作。

请怜悯我,哈哈谢谢。

当找到的定位点是第一个定位点时,您的代码会尝试访问 anchors[-1].name ,这会导致错误。

检查以查找循环中的第一个定位点,而不是在循环之后。

for (var i=0, iLen=anchors.length; i<iLen; i++) {
  if (anchors[i].name == anchorName) {
    if (i == 0) {
        prevAnchorName = anchors[(anchors.length - 1)].name;
    } else {
        prevAnchorName = anchors[i - 1].name;
    }
    break;
  }
 }
}

您也可以在循环之前执行此检查,并在 i = 1 处启动循环。

if (anchors[0].name == anchorName) {
    prevAnchorName = anchors[(anchors.length - 1)].name;
} else {
    for (var i=1, iLen=anchors.length; i<iLen; i++) {
        if (anchors[i].name == anchorName) {
            prevAnchorName = anchors[i - 1].name;
        }
    }
}

最新更新