gpt4 book ai didi

javascript - 使用 jQuery 一键切换类并保存最后状态

转载 作者:行者123 更新时间:2023-12-03 01:20:23 25 4
gpt4 key购买 nike

所以我试图结合 stackoverflow 上发布的三个问题的答案; Save current state after jquery click function , Save data to local storage ,和 HTML5 local storage save .toggleClass 。我想要做的是使用 .one() 在两个类 onclick 之间切换来自 jQuery。然后在类(class)切换后。

我想保存最后添加的类(class)。到目前为止我的代码如下:

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>

我怎样才能实现这个目标?

Heads up: I know it's doable if I add the class into a Field in the Object; if using MongoDB for instance; having default as fa-meh and onclick using some AJAX will update the Field in the Object to fa-smile-beam. But it's required using LocalStorage.

Note: According to MDN, LocalStorage violates policy decision, so it's not the practice to save user interaction.

最佳答案

好吧,你可以做这样的事情。你的出发点的主要问题是你不能在同一个函数中完成它们。您将需要两个独立的函数。

  1. 来回切换状态。我建议使用 .on 绑定(bind)方法而不是 .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')
}
});
});

关于javascript - 使用 jQuery 一键切换类并保存最后状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51795068/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com