如何使 JS 中的 window.history.back()
函数不受 HTML 中的 href="#"
影响?
因为现在当我第一次点击网页底部的 href="#"
时,我会回到页面顶部(正如它所指出的那样)。但是,当我点击 window.history.back()
函数时,当我真正想要的时候,我会被引导回页面底部的 href="#"
定向到上一页。
HTML:
<a href="#">Back to top</a>
<button class="klick" onclick="goBack()">Back</button>
JS:
function goBack() {window.history.back();}
感谢您的帮助。
最诚挚的问候果冻
最佳答案
您可以替换当前位置,而无需向 session 历史记录添加新状态。您可以使用 location.replace 来执行此操作方法,如下图。 (或者,您可以使用 history.replaceState 。)
<a class="toTop" href="#">Back to top</a>
document.addEventListener("click", goToTop);
function goToTop(event){
if(event.target.classList.contains("toTop")){ // Will work for multiple `.toTop` elements
event.preventDefault(); // Because this is an anchor element w/ href attribute
location.replace(location.href); // Navigates without updating history
}
}
关于javascript - 如何使我的 window.history.back() 函数忽略 href ="#"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65818536/