首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >本地存储循环

本地存储循环
EN

Stack Overflow用户
提问于 2013-01-10 19:03:54
回答 1查看 312关注 0票数 0

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

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

我已经让它在列表中的第一个切换滑块工作,但我想做的是循环通过每个滑块,并为每个滑块,保存它的'id‘和'value’到本地存储。然后,一旦保存,在页面加载时,恢复它们,并根据它在本地存储中的内容更改切换开关。

下面是我的代码:

代码语言:javascript
运行
复制
//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());
});

好的,这样就行了,在本地存储中,我得到了以下内容:

代码语言:javascript
运行
复制
Key: #flip-min-1    Value: yes or no depending on choice as it is a toggle slider

现在,当浏览器关闭并重新打开时,我从本地存储中检索数据,并使用它来根据它所说的内容来切换滑块:

代码语言:javascript
运行
复制
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和值保存在本地存储中!

我真的需要帮助,如果有人愿意提时间的话,我将不胜感激,谢谢你,汤姆

EN

回答 1

Stack Overflow用户

发布于 2013-01-10 19:51:50

如果你有固定数量的开关,简单地把所有东西都放在一个for循环中,例如

代码语言:javascript
运行
复制
for(var i = 0; i < 5; i++) {
    $("#button" + i).click(function() {
        window.localStorage.setItem('flip-min-' + i, $("#flip-min-" + i).val());
    });
}

否则,您可以为它们提供一个类和一个数据属性,如下所示:

代码语言:javascript
运行
复制
<button class="mySwitch" data-number="1">Switch 1</button>
<button class="mySwitch" data-number="2">Switch 2</button>

并使用如下代码

代码语言:javascript
运行
复制
// 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
  }
});
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/14256430

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档