我需要制作两个(或更多)按钮,在我关闭浏览器后将保存,以便我打开它 我将有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>
答案 0 :(得分:1)
是否只有两个这样的按钮应该起作用:
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;
}
}
答案 1 :(得分:1)
为了执行此任务的泛型函数,在按钮中使用类名来从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>