[英]Save toggle state + class toggle using cookies
我有大約4個按鈕,它們在單擊時顯示內容
$(function() {
$(".hidden").hide();
$('.button').on('click', function() {
var circle = $(this).attr('data-circle');
$('.'+circle).toggle();
$(this).find('i').toggleClass('fa-minus fa-plus');
});
});
我的HTML
<button class="button" data-circle="biographies">
<i class="fa fa-plus"></i> biographies
</button>
<button class="button" data-circle="pictures">
<i class="fa fa-plus"></i> pictures
</button>
<button class="button" data-circle="poetry">
<i class="fa fa-plus"></i> poetry
</button>
<div class="biographies hidden">content</div>
<div class="pictures hidden">content</div>
<div class="poetry hidden">content</div>
內容是隱藏的,因為我想在每次單擊時都將其顯示出來,正如您所看到的,我還在使用超棒的字體,這在內容可見時給了我一個加號,而在隱藏時給了我一個減號。
如何保存內容和圖標類的切換狀態?
轉到此處獲取有關Cookie的簡單教程: http : //www.w3schools.com/js/js_cookies.asp
將以下函數添加到您的JS中(當然要對其進行一些修改以刪除警報語句,等等):setCookie()和getCookie()
然后,在頁面加載時,使用“ getCookie('toggleStatus')”檢查cookie是否已經存在(假設您將cookie命名為“ toggleStatus”)。 如果它們不存在,請使用以下命令創建盡可能多的它們:
setCookie('toggleStatus','hidden', 30);
setCookie('toggleStatus2','hidden', 30);
等等....
如果它們確實存在,則相應地更新按鈕的狀態。
然后在每個按鈕上單擊,檢查cookie的當前值,並相應地更新它們:
if(getCookie('toggleStatus') === 'hidden') {
setCookie('toggleStatus', 'show', 30);
} else {
setCookie('toggleStatus', 'hidden', 30);
}
這是未經測試的答案,可能有或沒有錯別字:)
一位redditor同事對此提供了幫助,並建議我使用本地存儲,這是是否有人想要答案
var localStorageKey = "app_state";
// to preserve state, you first need to keep track of it
var default_state = {
biographies: false,
pictures: false,
poetry: false
}
var saved_state = localStorage.getItem(localStorageKey);
// ternary operator which means if `saved_state` evaluates to `true` we parse it and use that value for `state`; otherwise use `default_state`
var state = saved_state ? JSON.parse(saved_state) : default_state;
$(function() {
init();
$('.button').on('click', function() {
var circle = $(this).attr('data-circle');
toggleCircle(circle, !state[circle]);
$(this).find('i').toggleClass('fa-minus fa-plus');
});
function init() {
for(var key in state) {
var is_displayed = state[key];
console.log(});is_displayed);
toggleCircle(key, is_displayed);
}
}
function toggleCircle(circle, is_displayed) {
if (is_displayed) {
$('.'+circle).show()
state[circle] = true;
} else {
$('.'+circle).hide()
state[circle] = false;
}
localStorage.setItem(localStorageKey, JSON.stringify(state));
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.