2013-01-10 31 views
0

我想獲得一些本地存儲在我的網站上工作,我掙扎着。本地存儲迴路

我有幾個「切換滑塊」(如: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 

現在,當瀏覽器被關閉並重新打開,我從當地retreive數據存儲和使用它切換滑塊取決於它說:

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 
} 

我正在努力與事實上,我有多個切換開關和foreach我需要保存它的id和值在本地存儲!

我真的需要幫助,如果任何人能好心提出自己的時間,我將不勝感激,在此先感謝,湯姆

+0

1'='標誌的比較你的?不好... – marekful

+0

是的,我正急着把這個問題拿出來...... – user1966431

+0

如果它對你有用,你可以將這個問題標記爲回答 –

回答

0

如果你有開關的固定號碼,只需把一切都放在一個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 
    } 
}); 
+0

嗨,馬克斯,謝謝你的答覆,現在沒有多少時間,但它看起來像我需要使用你的第二個解決方案。我會盡快給它,讓你知道我如何得到感謝! – user1966431