[英]localstorage more than 1 button
我需要制作2个(或更多个)按钮,这些按钮将在我关闭浏览器后保存,以便如果我打开它,我将拥有2个白色按钮,而不是2个蓝色按钮。 那么,如何在不为每个按钮执行不同功能的情况下保存每个按钮呢?
<script>
function save() {
var storeButton = document.getElementById("testButton1");;
localStorage.setItem("buttonColor", storeButton.style.backgroundColor);
}
function load() {
var color = localStorage.getItem("buttonColor");
if (color) {
document.getElementById("testButton1").style.backgroundColor = color;
}
}
</script>
<body onload="load()">
<input type="button" id="testButton" value="Save" onclick="save()"/>
<input class="blue" type="button" id="testButton1" value="click me to turn white" style="background-color:blue" onclick="changeBlue(this)">
<input class="blue" type="button" id="testButton2" value="click me to turn white" style="background-color:blue" onclick="changeBlue(this)">
</body>
是否只有两个按钮应该可以正常工作:
function save() {
var storeButton = document.getElementById("testButton1");;
localStorage.setItem("buttonColor1", storeButton.style.backgroundColor);
storeButton = document.getElementById("testButton2");;
localStorage.setItem("buttonColor2", storeButton.style.backgroundColor);
}
function load() {
var color = localStorage.getItem("buttonColor1");
if (color) {
document.getElementById("testButton1").style.backgroundColor = color;
}
color = localStorage.getItem("buttonColor2");
if (color) {
document.getElementById("testButton2").style.backgroundColor = color;
}
}
为了执行此任务的通用功能,请在按钮中使用类名从DOM获取所有它们的引用并对其进行迭代,如下所示:
<script>
function save() {
var buttonList = document.getElementsByClassName("save-button-style");
var button;
for (var i = 0; i < buttonList.length; i++) {
button = buttonList[i];
localStorage.setItem(button.id, button.style.backgroundColor);
}
}
function load() {
var buttonList = document.getElementsByClassName("save-button-style");
var button;
for (var i = 0; i < buttonList.length; i++) {
button = buttonList[i];
var color = localStorage.getItem(button.id);
if (color) {
button.style.backgroundColor = color;
}
}
}
</script>
<body onload="load()">
<input type="button" id="testButton" value="Save" onclick="save()" />
<input class="blue save-button-style" type="button" id="testButton1" value="click me to turn white" style="background-color:blue" onclick="changeBlue(this)">
<input class="blue save-button-style" type="button" id="testButton2" value="click me to turn white" style="background-color:blue" onclick="changeBlue(this)">
</body>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.