私はスタッフがオフィス内外にあるかどうかを設定できるトグル入力を作成しました。私はローカルストレージを使用して入力の状態を保存しています。ページに複数のトグル入力を追加すると、各入力の状態を変更することができますが、ページをリロードすると、最後の入力に設定されたローカル記憶域(つまりすべてから出力)によってすべての入力が同じになります。ローカルストレージに応じて要素のスタイルを変更します
各トグル状態を保存し、これを覚えておくためにローカルストレージを使用するにはどうすればよいですか?
CSSコード
<style type="text/css">
.toggle {
-webkit-appearance: none;
appearance: none;
width: 150px;
height: 60px;
display: inline-block;
position: relative;
border-radius: 50px;
overflow: hidden;
outline: none;
border: none;
cursor: pointer;
background-color: red;
transition: background-color ease 0.3s;
}
.toggle:before {
content: "in out";
display: block;
position: absolute;
z-index: 2;
width: 80px;
height: 70px;
top: -5px;
left: -10px;
background: #fff;
border-radius: 50%;
font: 30px/70px Helvetica;
text-transform: uppercase;
font-weight: bold;
text-indent: -40px;
word-spacing: 85px;
color: #fff;
text-shadow: -1px -1px rgba(0,0,0,0.15);
white-space: nowrap;
box-shadow: 0 1px 2px rgba(0,0,0,0.2);
transition: all cubic-bezier(0.3, 1.5, 0.7, 1) 0.3s;
}
.toggle:checked {
background-color: #4CD964;
}
.toggle:checked:before {
left: 75px;
}
.toggle.in {
background-color: #4CD964;
}
.toggle.in:before {
left: 75px;
}
</style>
HTMLコード
<input class="toggle" type="checkbox" />
<input class="toggle" type="checkbox" />
jQueryのCODE
var toggle = $('.toggle');
toggle.on('click', function(){
if ($('input[type=checkbox]:checked').length === 0) {
localStorage.setItem('result', 'out');
$(this).removeClass('in');
} else {
localStorage.setItem('result', 'in');
$(this).addClass('in');
}
})
if (localStorage.result === 'in') {
toggle.addClass('in');
} else {
toggle.removeClass('in');
}
あなたは常にあなたのlocalStorage( 'result')で同じ場所をoverwriteingしています。それらを別々に保存するか、文字列化されたオブジェクト/配列として保存する必要があります。 – Zammy
最良の結果を得るには、各入力に 'ID'を使用し、オブジェクトの各入力にlocalStorage値を渡します。 –