javascript - jQuery - 在点击事件上切换 localStorage
问题描述
我正在尝试制作一个保存在本地存储中的收藏按钮,您可以打开和关闭。
但是我在点击时无法切换本地存储值。
这就是我所拥有的:
$(fav).click(function(){
localStorage.setItem('favourited', 'yes');
$(this).toggleClass('favourite');
});
我尝试过使用removeItem
是否在加载时设置了该项目,但这只会将其删除一次并且不允许切换。
解决方案
您可以使用该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>
推荐阅读
- reactjs - 如何从另一个组件的 onclick 事件中触发函数
- java - 我们如何使用 Java 函数实现 add(4)(10)(20)(3)(1).total?
- c - 为什么通过两个循环递增后变量值达到5050?(循环到 100)
- java - 具有匿名内部类的双重通用链表(在函数中)
- maven - YET ERROR StatusLogger 找不到 Log4j 2 配置文件。使用默认配置
- blueprism - 用于提取收集数据的蓝色棱镜代码阶段
- c# - C# 不能隐式转换类型'System.Collections.Generic.List
' 到 'System.Windows.Documents.List' - javascript - 将 { queue: false } 传递给 jQuery show()
- powershell - Linux 上的 PowerShell 配置文件位置是什么?
- java - 如何使用java processbuilder在su下运行命令?