【问题标题】:How to store state of disable button(s) even after refreshing a page?即使在刷新页面后如何存储禁用按钮的状态?
【发布时间】:2019-12-23 10:56:02
【问题描述】:

我的页面上有两个按钮。如果用户单击一个,则另一个将被禁用,反之亦然。假设如果启用了 'Button1'。这意味着 'Button2' 被禁用。现在,当我点击“按钮 2”时......“按钮 1”被禁用但是,当我刷新页面时,“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);

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

【问题讨论】:

  • 您可以使用 localStorage/sessionStorage、cookies 或服务器端数据存储(通过 AJAX 访问)来保持状态。哪种情况最适合您的情况取决于您希望状态保持多长时间,以及它需要有多安全
  • 将值存储到浏览器本地存储中并从那里加载
  • @RoryMcCrossan 感谢您的回复。我是 JS/jQuery 新手,请问可以要求做一个小演示吗?

标签: javascript jquery html


【解决方案1】:

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

localStorage

只读的localStorage 属性允许您访问文档来源的存储对象;存储的数据跨浏览器会话保存。 localStoragesessionStorage 类似,不同之处在于虽然localStorage 中存储的数据没有过期时间,但sessionStorage 中存储的数据会在页面会话结束时(即页面关闭时)被清除。

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
  .....
});

【讨论】:

  • sessionstorage 和 localstorage 有什么区别?
  • @danny_boy,存储在localStorage 中的数据没有过期时间,存储在sessionStorage 中的数据在页面会话结束时被清除:)
  • @danny_boy localStorage 是每个域的存储,sessionStorage 是每个会话的存储。例如,如果您在两个不同的选项卡中打开您的应用,您可以通过 localStorage 共享数据,但它们的 sessionStorage 对它们每个都是私有的。
  • 您的解决方案是我正在寻找的解决方案。你能解释一下你做了什么吗?
  • @danny_boy 在您决定使用哪个(sessionStoragelocalStorage)之后,这应该取决于您的需要(您希望按钮的状态即使在您关闭选项卡并打开后也保持不变是后天吗?还是只是为了刷新?)每次更改按钮时,您都应该在其中保留按钮的状态(sessionStorage.setItem('buttonState', state))。加载页面时,从保存的数据(sessionStorage.getItem('buttonState'))中读取状态并相应地更改按钮的状态。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-17
  • 2021-06-07
  • 2015-11-22
  • 1970-01-01
  • 1970-01-01
  • 2014-10-21
相关资源
最近更新 更多