我正在尝试让一些本地存储在我的网站上工作,但我正在努力。
我有几个“切换滑块”(像这些:http://jquerymobile.com/test/docs/forms/switch/#),我想将用户的选择保存到本地存储中,这样当用户返回时,他们仍然可以看到他们以前的选择。
我已经让它在列表中的第一个切换滑块工作,但我想做的是循环通过每个滑块,并为每个滑块,保存它的'id‘和'value’到本地存储。然后,一旦保存,在页面加载时,恢复它们,并根据它在本地存储中的内容更改切换开关。
下面是我的代码:
//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和值保存在本地存储中!
我真的需要帮助,如果有人愿意提时间的话,我将不胜感激,谢谢你,汤姆
发布于 2013-01-10 19:51:50
如果你有固定数量的开关,简单地把所有东西都放在一个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
}
});
https://stackoverflow.com/questions/14256430
复制相似问题