2017-01-01 58 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)