如何编码一个按钮,单击该按钮会更改颜色(或禁用它)并保持该页面的所有下一个实例的那种方式?
目前看来是这样的
function res1() {
var bgcolor = document.getElementById("hideshow").style.background = "gray";
var fontcolor = document.getElementById("hideshow").style.color = "white";
var text = document.getElementById("hideshow").innerHTML = "Reserved";
localStorage.setItem("hideshow").style.background.value = bgcolor;
localStorage.setItem("hideshow").style.color.value = fontcolor;
localStorage.setItem("hideshow").innerHTML.value = text;
document.getElementById("hideshow").style.background = bgcolor;
document.getElementById("hideshow").style.color = fontcolor;
document.getElementById("hideshow").innerHTML = text;
}
答案 0 :(得分:0)
localStorage
只能存储字符串,因此我们的想法是存储您想要保留的每个按钮的状态。为此,我们可以创建一些简单的函数:
localStorage
// Create a variable storing the buttons
const btns = document.querySelectorAll('.btn');
// Retrieve the button state from localStorage and each
// button's state
const getBtnState = function (btns) {
[].forEach.call(btns, function(btn) {
if (window.localStorage.getItem(btn.id) == 'disabled') {
btn.disabled = true
}
});
};
// Add an event listener to each button to
// disable and store the button's state on click
[].forEach.call(btns, function(btn) {
btn.addEventListener('click', function (e) {
btn.disabled = true
window.localStorage.setItem(btn.id, 'disabled')
})
});
// Call the getBtnState function to set the initial state
// of each button
getBtnState(btns);

<button id="btn1" class="btn">Button 1</button>
<button id="btn2" class="btn">Button 2</button>
<button id="btn3" class="btn">Button 3</button>
<button id="btn4" class="btn">Button 4</button>
&#13;
此演示不适用于Stackoverflow,因为该演示是沙盒式的#39;。对于工作演示,请转到此Codepen demo。
答案 1 :(得分:0)
由于您的样式无论如何都是硬编码的,因此无需将它们存储在localStorage中。
这是一个更简单的实现:
document.onload = function(){
if (localStorage.getItem("buttonHasBeenClicked")){
// make the button grey and change text etc. here
// also, you said you wanted to disable it?
document.getElementById("hideshow").disabled = 'disabled';
}
document.getElementById("hideshow").addEventListener('click', function(e){
localStorage.setItem("buttonHasBeenClicked",true);
}
};
关于你所拥有的东西的旁注:
localStorage.setItem("hideshow").style.background.value = bgcolor;
这会破坏因为setItem不返回任何内容。您传入要存储的对象作为第二个参数(我传递的值为true,上面)