问题描述
我对 JavaScript 非常陌生。我正在尝试制作一个 Web 应用程序,其中一个简单的后退按钮将转到我正在查找的特定页面,其中包含“搜索”一词。我不知道确切的 URL,因为该 URL 中的参数会发生变化,我需要使其与用户想要的保持一致。但是这个按钮应该回到那个页面,而不管点击了其他链接。 例如: 如果我点击
Home Page
Main Page
Page 1
Page 1.3
Back
我希望返回总是带我到主页,并使用它之前的确切参数,而不是主页。
我尝试了以下方法: 按钮本身
movieTableBodyElement.append('<a href="#" onclick="javascript:goBackHelper();">' + " << Back" + '</a>'); // Building the HTML button,calls the goBackHelper() function
function goBackHelper()
{
// checks if the page directly behind is the Main Page with "search"
if(document.referrer.includes("search"))
{
// if its the main page,exit the function and end recursive call
window.history.go(-1);
}
else
{
// it is not the last page,so go to the past page and check again
window.history.go(-1);
goBackFunction();
}
}
但这会将我带到第一个主页。我以为 document.referrer 会让我得到过去的 URL,但它似乎对我不起作用。有没有办法从过去的页面中获取 URL?因此,如果我在第 2 页上,我可以获取所有 URL 并搜索主页吗?非常感谢任何帮助!
我也是 Stack Overflow 的新手,所以如果有任何说明,请随时告诉我!
解决方法
document.referrer
并非在所有情况下都与实际 URL 相同。
最好的办法是将 URL 存储在 sessionStorage
中。
将此代码段添加到您的页面:
if (sessionStorage.getItem("locationHistory") !== null) {
var locationHistoryArray = JSON.parse(sessionStorage.getItem("locationHistory"));
locationHistoryArray.push(window.location.href);
sessionStorage.setItem("locationHistory",JSON.stringify(locationHistoryArray));
} else {
var locationHistoryArray = [];
locationHistoryArray.push(window.location.href);
sessionStorage.setItem("locationHistory",JSON.stringify(locationHistoryArray));
}
这是你的 goBackHelper()
函数:
function goBackHelper() {
var searchString = 'search'; //modify this
var locationHistoryArray = JSON.parse(sessionStorage.getItem("locationHistory"));
for (i = 0; i < locationHistoryArray.length; i++) {
if (locationHistoryArray[i].includes(searchString)) {
window.location.assign(locationHistoryArray[i]);
break;
}
}
}
了解 document.referrer
here。