Javascript 本地存储环路

Javascript 本地存储环路,javascript,jquery,local-storage,Javascript,Jquery,Local Storage,我正试图让一些本地存储在我的网站上工作,我正在努力 我有几个“切换滑块”(如下:),我想将用户的选择保存到本地存储中,这样当用户返回时,他们仍然可以看到以前的选择 我已经让它在列表中的第一个切换滑块工作,但是我想做的是循环通过每个滑块,并为每个滑块保存其“id”和“值”到本地存储。保存后,在页面加载时,根据本地存储中显示的内容恢复这些内容并更改切换开关 这是我的密码: //code below saves id and value to local storage when save butto

我正试图让一些本地存储在我的网站上工作,我正在努力

我有几个“切换滑块”(如下:),我想将用户的选择保存到本地存储中,这样当用户返回时,他们仍然可以看到以前的选择

我已经让它在列表中的第一个切换滑块工作,但是我想做的是循环通过每个滑块,并为每个滑块保存其“id”和“值”到本地存储。保存后,在页面加载时,根据本地存储中显示的内容恢复这些内容并更改切换开关

这是我的密码:

//code below saves id and value to local storage when save button is clicked
$("#button").click(function() {
    window.localStorage.setItem('flip-min-1', $("#flip-min-1").val());
});
好的,这样就可以了,在本地存储中,我得到了以下信息:

Key: #flip-min-1    Value: yes or no depending on choice as it is a toggle slider
现在,当浏览器关闭并重新打开时,我将从本地存储中检索数据,并根据其显示的内容使用它切换滑块:

var storedText = window.localStorage.getItem('flip-min-1');

//if the variable in local storage is equal to yes
if(storedText = 'yes') {
    //then switch the toggle slider to the yes state so it appear in red and reads 'Attending'
    $("#flip-min-1").val(window.localStorage.getItem('flip-min-1')).keyup();
    //if the stored text is anything other than yes, the default select option will be no. By default the user is not attending any events
}
我正在努力解决的是,我有多个切换开关,对于每个开关,我都需要将其id和值保存在本地存储中


我真的需要帮助,如果有人愿意提出他们的时间,我将不胜感激,提前谢谢,Tom如果你有固定数量的开关,只需将所有东西放在一个for循环中,例如

for(var i = 0; i < 5; i++) {
    $("#button" + i).click(function() {
        window.localStorage.setItem('flip-min-' + i, $("#flip-min-" + i).val());
    });
}

与1比较
=
登录您的if??不太好…是的,我正赶着把这个问题提出来…如果它对你有用,你可能会把这个问题标记为已回答Hi Max,谢谢你的回答,现在没有太多时间,但在我看来,我需要使用你的第二个解决方案。我会很快试一试,让你知道我的进展如何谢谢!
<button class="mySwitch" data-number="1">Switch 1</button>
<button class="mySwitch" data-number="2">Switch 2</button>
// find all switches
$(".mySwitch")
// handle click event and save
.click(function() {
  var index = $(this).attr("data-number");
  window.localStorage.setItem('flip-min-' + index, $("#flip-min-" + index).val());
});
// load all states
.each(function() {
  var index = $(this).attr("data-number");
  var storedText = window.localStorage.getItem('flip-min-' + index);

  //if the variable in local storage is equal to yes
  if(storedText = 'yes') {
      //then switch the toggle slider to the yes state so it appear in red and reads 'Attending'
      $("#flip-min-1").val(window.localStorage.getItem('flip-min-' + index)).keyup();
      //if the stored text is anything other than yes, the default select option will be no. By default the user is not attending any events
  }
});