页面上有两个按钮。如果用户单击一个,则另一个将被禁用,反之亦然。假设是否启用了'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);
刷新页面后如何存储禁用按钮的最后状态?
答案 0 :(得分:7)
您可以将状态存储在sessionStorage
或localStorage
中,并在页面加载时使用该状态来设置属性:
只读的
localStorage
属性允许您访问文档来源的存储对象;存储的数据跨浏览器会话保存。localStorage
与sessionStorage
相似,不同之处在于尽管存储在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
.....
});