首页 > 解决方案 > jQuery - 在点击事件上切换 localStorage

问题描述

我正在尝试制作一个保存在本地存储中的收藏按钮,您可以打开和关闭。

但是我在点击时无法切换本地存储值。

这就是我所拥有的:

$(fav).click(function(){
      localStorage.setItem('favourited', 'yes');
      $(this).toggleClass('favourite');
});

我尝试过使用removeItem是否在加载时设置了该项目,但这只会将其删除一次并且不允许切换。

标签: javascriptjquerylocal-storage

解决方案


您可以使用该hasClass()方法检查类是否存在,然后根据该方法切换 localStorage:

$(fav).click(function() {
  // if there is a class we set "No" to local storage
  // because the code for toggle will remove that class from the HTML
  var value = $(this).hasClass('favourite') ? 'No' : 'yes';
  localStorage.setItem('favourited', value);
  $(this).toggleClass('favourite');
});

插图

var fav = $('.btn');
$(fav).click(function() {
  // if there is a class we set "No" to local storage because the code for toggle will remove that class from the HTML
  var value = $(this).hasClass('favourite') ? 'No' : 'yes';
  console.log(value);
  $(this).toggleClass('favourite');
});
.favourite {
  color: green;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<button class="btn">Click</button>


推荐阅读