The solution presented in the accepted answer has the important issue that it can only be used 1 time.(接受的答案中提出的解决方案具有一个重要问题,即只能使用1次。)
Each consecutive click appends #goToPage
to location and the window won't navigate to the anchor.(每次连续单击都会将#goToPage
附加到位置,并且该窗口将不会导航到锚点。)
A solution is to remove the anchor part before appending a new anchor:(一种解决方案是在附加新锚之前先删除锚部分:)
function goToAnchor(anchor) {
var loc = document.location.toString().split('#')[0];
document.location = loc + '#' + anchor;
return false;
}
Usage example:(用法示例:)
<a href="#anchor" onclick="goToAnchor('anchor')">Anchor</a>
NOTE: The anchor needs to be enclosed in quotes, without the hash prefix.(注意: 锚需要用引号引起来,而没有哈希前缀。) 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…