簡體   English   中英

使用jQuery一鍵切換類並保存上一個狀態

[英]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>

我該如何實現?

注意:我知道將類添加到ObjectField中是可行的; 如果使用MongoDB例如; 默認為fa-meh和使用某些AJAX onclick會將ObjectField更新為fa-smile-beam 但是使用LocalStorage是必需的。

注意:根據MDN的說法,LocalStorage違反了策略決策,因此,這不是保存用戶交互的做法。

好吧,你可以做這樣的事情。 起點的主要問題是您不能在同一功能中進行操作。 您將需要兩個單獨的功能。

  1. 來回切換狀態。 我建議使用.on綁定方法而不是.one,除非您不希望用戶能夠撤消其操作。

  2. 加載文檔時,除非有其他設置按鈕正確狀態的方法,否則必須設置狀態,該狀態保存在按鈕的本地存儲中。

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM