我正在尝试完成一门类(class)的家庭作业,我已经从 YouTube 视频中写了这篇文章,但它不起作用!!它是关于在 html 页面中添加 2 个按钮以在 css 类之间切换,并使用本地存储 API 将最后的选择保存在本地,当加载页面时它会记住最后的选择。
function applyTheme (theme) {
"use strict"
document.getElementById("mypage").className = theme;
localStorage.setItem ("theme", theme);
}
function applyDayTheme () {
"use strict"
applyTheme("day");
}
function applyNightTheme() {
"use strict"
applyTheme("night");
}
function addButtonLestenrs () {
"use strict"
document.getElementById("b1")addEventListener("click", applyDayTheme);
document.getElementById("b2")addEventListener("click", applyNightTheme);
}
function initiate(){
"use strict"
if(typeof(localStorage)===undefined)
alert("the application can not be executed properly in this browser");
else{
if(localStorage.getItem("theme")===null)
applyDayTheme();
else
applyTheme(localStorage.getItem("theme"));
}
addButtonLestenrs();
}
initiate();
.day{
color:black;
background-color:lightgrey;
}
.night{
color:white;
background-color:black;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="css/style.css">
</head>
<body id="mypage">
<h1>Choose a theme</h1>
<button id="b1">Theme day</button>
<button id="b2">Theme night</button>
<p> This is an example of use of HTML5 storage API </p>
<script type="text/javascript" src="js/script.js">
</body>
</html>
最佳答案
此代码的唯一问题是 .
丢失
document.getElementById("b1").addEventListener("click", applyDayTheme);
document.getElementById("b2").addEventListener("click", applyNightTheme);
该代码将运行良好,您也可以在脚本的第一个开头使用 'use strict'
。
关于Javascript 本地存储 API 主题切换不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44488510/