[英]Toggle classes one click using jQuery and save last state
因此,我試圖結合此處在stackoverflow上發布的三個問題的答案; jQuery單擊功能后保存當前狀態 , 將數據保存到本地存儲 , HTML5本地存儲保存.toggleClass 。 我想做的是使用jQuery中的.one()
在兩個類的onclick
之間切換。 然后在切換類別之后。
我想保存最后添加的課程。 到目前為止,我的代碼如下:
jQuery的
$(".post-tag").one('click', function() {
$(this).find('i').toggleClass('fa-meh fa-smile-beam text-warning text-success');
var likeState = $(this).find('i').hasClass('fa-smile-beam');
localStorage.setItem('liked', likeState);
var likedStorage = localStorage.getItem('liked');
if(likedStorage && $(this).find('i').hasClass('fa-smile-beam')) {
$(this).find('i').removeClass('fa-meh')
}
});
HTML
<div class="post-tag-wrapper">
<div class="post-tag shadow">
<i class="far fa-meh text-warning"></i>
</div>
</div>
我該如何實現?
注意:我知道將類添加到
Object
的Field
中是可行的; 如果使用MongoDB
例如; 默認為fa-meh
和使用某些AJAX
onclick
會將Object
的Field
更新為fa-smile-beam
。 但是使用LocalStorage
是必需的。注意:根據MDN的說法,LocalStorage違反了策略決策,因此,這不是保存用戶交互的做法。
好吧,你可以做這樣的事情。 起點的主要問題是您不能在同一功能中進行操作。 您將需要兩個單獨的功能。
來回切換狀態。 我建議使用.on綁定方法而不是.one,除非您不希望用戶能夠撤消其操作。
加載文檔時,除非有其他設置按鈕正確狀態的方法,否則必須設置狀態,該狀態保存在按鈕的本地存儲中。
HTML
<button class="post-tag" id="some-unique-id">
<i class="fa-meh"></i> Like
</button>
JavaScript的
// This will make sure that the state is toggled on user click
// The user can click back and forth, and the state will be saved each time
$(".post-tag").on('click', e => {
const $elm = $(e.currentTarget);
// If you have more than one button you'll need unique IDs for them to make this work
const uniqueId = $elm.attr('id');
const $i = $elm.find('i');
$i.toggleClass('fa-meh fa-smile-beam text-warning text-success');
const likeState = $i.hasClass('fa-smile-beam');
localStorage.setItem(`likeState-${id}`, likeState);
});
// To persist the change you'll have to run this on page load as well
$( document ).ready(function() {
const $postTags = $('.post-tag');
$postTags.each((elm) => {
const $elm = $(elm);
const uniqueId = $elm.attr('id');
const $i = $elm.find('i');
// Now you apply the state stored in local sotrage to your buttons.
const likedStorage = localStorage.getItem(`likeState-${id}`);
if(likedStorage && $i.hasClass('fa-smile-beam')) {
$i.removeClass('fa-meh')
}
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.