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

identify and jump to last anchor on document

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;
}

我从另一个 Whosebug 问题中得到了这一部分,锚 [(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 更改为一个函数。)

我理解我 hacked/assembled 一起编写的脚本的方式是,如果 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;
        }
    }
}