简体   繁体   English

将按钮 state 保存在 cookie 中或 Jquery 中的 localStorage

[英]Persist button state in a cookie or localStorage in Jquery

I am trying to persist a button state in a cookie for a certain amount of time using either cookies (cookie.js library) or LocalStorage.我正在尝试使用 cookies(cookie.js 库)或 LocalStorage 将按钮 state 在 cookie 中保留一段时间。 I have not done this before so I am not sure how I can approach it.我以前没有这样做过,所以我不确定如何处理它。

The state I want to persist for at least a day would be changing the button's text using Jquery text function as follows:我想坚持至少一天的 state 将使用 Jquery 文本 function 更改按钮的文本,如下所示:

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

This action would pretty much be done on an onClick event.这个动作几乎可以在 onClick 事件上完成。

Local storage is vanilla JS, it works with or without jQuery.本地存储是 vanilla JS,它可以在有或没有 jQuery 的情况下使用。 It's fairly simple:这很简单:

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

That stores it.那存储它。 Then to read it:然后阅读它:

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

From there you can do whatever you want with that text, including passing it into a jQuery function to set some DOM element's text or whatever else you want.从那里您可以对该文本执行任何操作,包括将其传递到 jQuery function 以设置某些 DOM 元素的文本或您想要的任何其他内容。

You will want to load that data on page load if you want to persist across reloads:如果您想在重新加载时保持不变,您将需要在页面加载时加载该数据:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM