我的页面上有两个按钮。如果用户单击其中一个,另一个将被禁用,反之亦然。假设'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
并在页面加载时使用它来设置属性:
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 tosessionStorage
, except that while data stored inlocalStorage
has no expiration time, data stored insessionStorage
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/