javascript - 即使刷新页面后如何存储禁用按钮的状态?

标签 javascript jquery html

我的页面上有两个按钮。如果用户单击其中一个,另一个将被禁用,反之亦然。假设'Button1'已启用。这意味着'Button2'被禁用。现在,当我点击“Button 2”时......“Button1”被禁用但是,当我刷新页面时,“Button1”将被启用,“Button2”将再次被禁用。如何保存上次禁用按钮的状态并在刷新页面后查看?

这是我到目前为止尝试过的:

template.html:

<button type="button" id ='button1'> Button 1 </button> 
<br> <br>
<button type="button" id ='button2' disabled /> Button 2 </button>

template.js(使用 Jquery):

    $('#button1').click(function () {
        $("#button1").attr("disabled", true);
        $("#button2").attr("disabled", false);

    $('#button2').click(function () {
        $("#button2").attr("disabled", true);
        $("#button1").attr("disabled", false);

如何在刷新页面后存储禁用按钮的最后状态?

最佳答案

您可以将状态存储在 sessionStorage 中或localStorage并在页面加载时使用它来设置属性:

localStorage

The read-only localStorage property allows you to access a Storage object for the Document's origin; the stored data is saved across browser sessions. localStorage is similar to sessionStorage, except that while data stored in localStorage has no expiration time, data stored in sessionStorage gets cleared when the page session ends — that is, when the page is closed.

var disbledBtn = localStorage.getItem('disabled'); // get the id from localStorage
$(disbledBtn).attr("disabled", true); // set the attribute by the id

$('#button1').click(function () {
  $("#button1").attr("disabled", true);
  $("#button2").attr("disabled", false);
  localStorage.setItem('disabled', '#button1'); // store the id in localStorage
  ......
});
$('#button2').click(function () {
  $("#button2").attr("disabled", true);
  $("#button1").attr("disabled", false);
  localStorage.setItem('disabled', '#button2'); // store the id in localStorage
  .....
});

关于javascript - 即使刷新页面后如何存储禁用按钮的状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59454119/

相关文章:

javascript - 如何在 Laravel 中使用 app.js 和 app.css 修复错误 404?

javascript - MediaRecorder API - 自动录制

php - 文本文件的 Sprite

javascript - 如何从异步调用返回响应?

jquery - 如何使用CSS变换实现两个多步表单,每边一个表单

javascript - 在 HTML 页面刷新时强制页面滚动位置到顶部

html - Chrome 中的 Google 搜索 <mark> 如何回答滚动后消失的网站

javascript - 如何在 sapui5 XML View 中显示 Controller 变量?

javascript - $.get 返回相同的数组

jquery - 单击标签不会选中关联的复选框