Javascript本地存储API主题切换无法正常工作

时间:2017-06-11 20:34:06

标签: javascript html api local-storage

我正在尝试做一个课程家庭作业,我从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>

1 个答案:

答案 0 :(得分:1)

此代码的唯一问题是.缺少

document.getElementById("b1").addEventListener("click", applyDayTheme);
document.getElementById("b2").addEventListener("click", applyNightTheme);

代码运行良好,您也可以在脚本的第一个开头使用'use strict'