我有一个包含多个页面的网站: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,可能不是最正确的措辞。
答案 0 :(得分:1)
我刚刚为您制作了一个超小型样品。希望它会有所帮助。
我们的静态网站将包含三个页面:
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>
<!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
与我们的网站站点地图相匹配方面做了一些工作。