2017-01-01 79 views
1

如何为单击代码更改颜色(或禁用它)并保留该页面的所有下一个实例的按钮?在本地存储器中存储禁用的按钮

这是它目前的样子

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

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>

由于演示为“沙盒”,此演示无法在Stackoverflow上运行。对于这个Codepen demo的工作演示头。

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)