Javascript 本地存储 API 主题切换不起作用

标签 javascript html api local-storage

我正在尝试完成一门类(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/

相关文章:

javascript - google地点详情API结果中返回了price_level

javascript - Microsoft Dynamics CRM 2015 计算字段如何工作?

javascript - 修改两个文件之间的对象

html - z-index 和 css 权威指南 图 10-55

javascript - 如何在进一步移动之前要求 JQuery 加载函数加载完整的页面内容

c# - TFS API 获取删除文件 - 更新到新版本后的不同行为(从 14xx 到 16xx)

api - 维基百科 API - 抓取 'Background Inforamtion' 表?

javascript - 为什么 forkJoin 从我的可观察量中返回错误的值?

javascript - Internet Explorer 不会显示带有嵌入式 jquery 的呈现的 gsp

html - 如何在 CSS 中更改图像背景位置?