javascript - 使用 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-meh
并onclick
使用 someAJAX
将更新toField
中的。但它需要使用.Object
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')
}
});
});
推荐阅读
- javascript - 解开 onMouseEnter、onMouseLeave 和 onClick 中的状态变化
- javascript - 为什么切换的类不会为元素设置动画并且控制台中没有错误
- vba - 在 Microsoft Access 中打开报表中的相应表单
- tensorflow - 使用 Gradient.Tape 计算自定义损失函数的梯度
- flutter - 使容器高度跟随项目
- python - 使用pyinstaller将python文件执行为exe后出错
- hive - hive 查询 presto 创建的表失败
- azure-data-factory - 使用 ADF 在 cosmos db 中记录文件名
- c++ - 如何根据类型制作具有重载函数的模板?
- autoencoder - 低维聚类会比高维更准确吗?