【问题标题】:Local Storage Loop本地存储循环
【发布时间】:2013-01-10 11:03:54
【问题描述】:

我正在尝试让一些本地存储在我的网站上运行,但我正在苦苦挣扎。

我有几个“切换滑块”(例如:http://jquerymobile.com/test/docs/forms/switch/#),我想将用户的选择保存到本地存储中,这样当用户返回时,他们仍然可以看到他们之前的选择。

我已经让它适用于列表中的第一个切换滑块,但是我想要做的是循环遍历每个滑块,并将其“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

【问题讨论】:

  • 比较 1 = 登录你的 if??不好...
  • 是的,我正着急把这个问题说出来……
  • 如果它对你有用,你可能会将此问题标记为已回答

标签: javascript jquery local-storage


【解决方案1】:

如果您有固定数量的开关,只需将所有内容放在 for 循环中,例如

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

否则,你可以给它们一个类和一个数据属性,比如:

<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
  }
});

【讨论】:

  • 嗨 Max,感谢您的回复,现在没有太多时间,但在我看来,我需要使用您的第二个解决方案。我会尽快试一试,让你知道我的进展如何,谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-10
  • 2014-03-19
  • 1970-01-01
  • 1970-01-01
  • 2015-01-19
  • 1970-01-01
相关资源
最近更新 更多