你只是忘记了Storage.setItem()。您声明您想要“保存”最近使用的样式表。
我认为你在这里混淆了状态的概念。在您的代码示例中,您从 localStorage 读取值 a,但您在任何时候都没有尝试设置 localStorage。
让我们看一个最小的例子。我准备了一个现场演示如下:
现场演示
假设您有这些文件:
索引.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>repl.it</title>
<link href="style.css" rel="stylesheet" type="text/css" />
<link id="active-stylesheet" href="" rel="stylesheet" type="text/css"/>
</head>
<body>
<div class="switch-buttons">
<button class="switch-buttons__light button" data-stylesheet="light.css">Go Light</button>
<button class="switch-buttons__dark button" data-stylesheet="dark.css">Go Dark</button>
</div>
<h1>Light and Dark Stylesheets with Web Storage API</h1>
<h2> See <a href="https://developer.mozilla.org/en-US/docs/Web/API/Storage">MDN Storage - Web Storage API</a>.</h2>
<p>
Click a button above. The style you select will be 'remembered' when you refresh this page. To reset this demo, click the 'Clear Storage' button.</p>
<p>
Faucibus interdum posuere lorem ipsum dolor sit amet, consectetur adipiscing elit duis tristique sollicitudin nibh sit amet commodo nulla facilisi? In metus vulputate eu scelerisque felis imperdiet proin fermentum leo.</p>
<p>
Etiam sit amet nisl purus, in mollis nunc sed id semper risus in! Ultricies lacus sed turpis tincidunt id aliquet risus feugiat in ante metus, dictum at tempor commodo, ullamcorper?</p>
<button id="clear-storage">Clear Storage</button>
<script src="script.js"></script>
</body>
</html>
光.css
body {
background-color: #fff0bc;
}
h1, h2, p {
color: #363636;
}
dark.css
body {
background-color: #363636;
}
h1, h2, p {
color: #fff0bc;
}
脚本.js
var buttons = document.getElementsByClassName("button");
var activeSheet = document.getElementById("active-stylesheet");
var clearStorageButton = document.getElementById("clear-storage");
// Test to see if localStorage already has a value stored
if (localStorage.getItem("lastActiveSheet")) {
activeSheet.setAttribute("href", localStorage.getItem("lastActiveSheet"));
}
// Assign the event lister to each button
for (var i = 0; i < buttons.length; i++) {
buttons[i].addEventListener("click", switchStyle);
}
// Create a button to clear localStorage
clearStorageButton.addEventListener("click", clearStorage);
// Set the #active-stylesheet to be the light or dark stylesheet
function switchStyle() {
var selectedSheet = this.getAttribute("data-stylesheet");
activeSheet.setAttribute("href", selectedSheet);
localStorage.setItem("lastActiveSheet", selectedSheet);
}
// Wrapper function to localStorage.clear
function clearStorage() {
localStorage.clear();
}
如果您希望您的应用程序记住最近使用的样式表,则需要将其存储到 localStorage 中,作为用户将来再次访问您的应用程序时可以使用的值。
正如@Hynek 所指出的,使用它不是一个好主意window.onLoad
。因此,在这个示例中,我将事件侦听器附加到所有使用的按钮上。
在此示例中,页面有两个选项可供选择:用于对比的浅色主题和深色主题。如果用户选择一个主题,下次刷新页面时将会记住该主题。
这里的关键是state。您希望您的应用程序具有“内存”。因此,您需要添加功能write, read, and clear记忆。我建议阅读更多内容MDN - 存储 - Web API看看如何实现这一点。 MDN 上还有更多示例!