在 Jquery 中的 cookie 或 localStorage 中保留按钮状态



我正在尝试使用cookie(cookie.js库(或LocalStorage将按钮状态在cookie中保留一定时间。我以前没有这样做过,所以我不确定我该如何处理它。

我想坚持至少一天的状态是使用 Jquery 文本函数更改按钮的文本,如下所示:

$(_this).text("Job already started or completed...");

此操作几乎可以在 onClick 事件上完成。

本地存储是原版 JS,无论是否使用 jQuery。这很简单:

localStorage.setItem('buttonText', 'Job already started or completed...');

存储它。然后阅读它:

const storedButtonText = localStorage.getItem('buttonText');

从那里你可以对那个文本做任何你想做的事情,包括把它传递给jQuery函数来设置一些DOM元素的文本或其他任何你想要的东西。

如果要在重新加载后保留,则需要在页面加载时加载该数据:

$(document).ready(function() {
const storedButtonText = localStorage.getItem('buttonText');
if (storedButtonText) {
$('#theButtonElement').text("Job already started or completed...");
}
});

最新更新