我有这个功能可以在点击按钮后禁用它,我怎样才能将状态保存在本地存储中。
cancelado: function() {
var x = document.getElementById("myBtn");
x.disabled = true;
}
最佳答案
每当您更改按钮的状态时,您都需要更新本地存储中的标志 - 您甚至可以编写一个同时执行这两项操作的函数,例如
function setButtonDisabled(state) {
// Update the button's state
document.getElementById("myBtn").disabled = state;
// Set the local storage flag to match
localStorage.setItem("myBtnState", state);
}
// Usage would be setButtonDisabled(true) to disable or
// setButtonDisabled(false) to enable
当您加载页面时,您需要获取该状态(如果它存在),并更新按钮,例如
// On page load (or in whatever event creates the button)
window.addEventListener("load", ()=>{
// Read the saved state from local storage (if not yet saved, will be null)
let myBtnState = localStorage.getItem("myBtnState");
if (myBtnState != null) { // If a state has been saved...
// ...reset the state of the button from the saved state
document.getElementById("myBtn").disabled = myBtnState == "true";
}
});
请注意,本地存储只能存储字符串(技术上是 DOMStrings),不能存储 bool 值(或数字、对象、函数等),因此我们传入的值( bool 值 true
或 false
) 将自动转换为 "true"
或 "false"
- 因此我们需要检查此值是否等于 的字符串值>"true"
将其转换回实际的 bool 值。
您可以在 MDN 阅读有关本地存储 API 的更多信息.
但是,我敢打赌,您要为其保存状态的元素不只一个。此外,这是一个非常“机械”的问题解决方案。最好保存某种表示页面状态的 JSON 对象,而不是该状态的效果。
例如,是什么导致按钮被禁用?假设这是因为用户在表单中输入了一个太大的数字。在这种情况下,最好将数字保存起来,因为这样不仅可以将其填回框中,而且如果没有数字填入框内,则按钮不应灰显。这也让我们可以更好地改变逻辑——如果我们提高了允许数字的最大值,那么在输入过去太小的数字后返回页面的用户仍然会发现该框是灰色的,而如果我们保存了数字,我们可以再次执行计算并意识到他们的号码现在有效。
关于javascript - 如何将我的数据保存在本地存储中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62185005/