我有一个包含多个页面的网站:page001.html、page002.html...page199.html...
我如何使用 localsave 让它记住用户所在的页面,并使用户在返回网站时能够加载同一页面?
我打算有保存和加载按钮。我只是对 setItem 和 getItem 在这种情况下的工作方式感到困惑。值应该是多少?
我试过这样的:
Page001.html
function savePage() {
localStorage.setItem("lastPageVisited", '001.html');
}
<p>This is page 001</p>
<a href="002.html">Go to the Next Page</a>
<button onclick="savePage()">Save</button>
Page002.html
function savePage() {
localStorage.setItem("lastPageVisited", '002.html');
}
function loadPage() {
localStorage.getItem("lastPageVisited");
window.location.href = 'LastPageVisited';
}
<p>This is page 002</p>
<a href="003.html">Go to the Next Page</a>
<button onclick="savePage()">Save</button>
<button onclick="loadPage()">Load</button>
我希望这个问题是有道理的。我仍在学习 javascript,可能没有用最正确的方式来表达它。
最佳答案
我刚刚为您制作了一个超小样本。希望对您有所帮助。
我们的静态网站将包含三个页面:
Index.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>Index</title>
</head>
<body>
<h2>This is the Index page</h2>
<a href="home.html">Home</a>
<a href="about.html">About</a>
<button onclick="savePage()">Save</button>
<button onclick="loadPage()">Load</button>
<script>
function savePage() {
localStorage.setItem("lastPageVisited", '/index.html');
}
function loadPage() {
const page = localStorage.getItem("lastPageVisited");
const pathname = window.location.pathname;
const url = window.location.href.replace(pathname, page);
window.location.replace(url);
}
</script>
</body>
</html>
Home.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>Home</title>
</head>
<body>
<h2>This is the Home page</h2>
<a href="index.html">Index</a>
<a href="about.html">About</a>
<button onclick="savePage()">Save</button>
<button onclick="loadPage()">Load</button>
<script>
function savePage() {
localStorage.setItem("lastPageVisited", '/home.html');
}
function loadPage() {
const page = localStorage.getItem("lastPageVisited");
const pathname = window.location.pathname;
const url = window.location.href.replace(pathname, page);
window.location.replace(url);
}
</script>
</body>
</html>
- About.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>About</title>
</head>
<body>
<h2>This is the About page</h2>
<a href="index.html">Index</a>
<a href="home.html">About</a>
<button onclick="savePage()">Save</button>
<button onclick="loadPage()">Load</button>
<script>
function savePage() {
localStorage.setItem("lastPageVisited", '/about.html');
}
function loadPage() {
const page = localStorage.getItem("lastPageVisited");
const pathname = window.location.pathname;
const url = window.location.href.replace(pathname, page);
window.location.replace(url);
}
</script>
</body>
</html>
这里的关键是使用 window.location.replace()
方法。此方法允许您用新文档替换当前文档。然后,在 window.location.replace()
方法的帮助下,我们只需做一些工作来计算 url string
以与我们的网站站点地图匹配。
关于Javascript - 将页面保存到本地存储,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52521708/