2017-01-01 10 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関数は何も返さないので、これが解除されます。 2番目のパラメータとして格納するオブジェクトを渡します(私は上記の値trueを渡しています)

関連する問題