首页 > 解决方案 > 使用 jQuery 一键切换类并保存上一个状态

问题描述

所以我试图结合stackoverflow上发布的三个问题的答案;jquery点击函数后保存当前状态将数据保存到本地存储HTML5本地存储保存.toggleClass。我想要做的是onclick使用.one()jQuery 在两个类之间切换。然后在切换类之后。

我想保存最后添加的课程。到目前为止,我的代码如下:

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>

我怎样才能做到这一点?

注意:我知道如果我将类添加到;中是可行Field的 例如,Object如果使用;MongoDB具有默认 asfa-mehonclick使用 someAJAX将更新to Field中的。但它需要使用.Objectfa-smile-beamLocalStorage

注意:根据MDN,LocalStorage 违反了策略决定,因此不是保存用户交互的做法。

标签: javascriptjquerybootstrap-4local-storagesession-storage

解决方案


好吧,你可以做这样的事情。您的起点的主要问题是您不能在同一个函数中执行它们。您将需要两个单独的功能。

  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')
    }
  });
});

推荐阅读