gpt4 book ai didi

javascript - 将禁用按钮存储在本地存储中

转载 作者:行者123 更新时间:2023-11-28 05:10:31 25 4
gpt4 key购买 nike

如何编写一个按钮,当单击该按钮时,该按钮会更改颜色(或禁用它)并在该页面的所有下一个实例中保持这种状态?

这就是目前的样子

function res1() {
var bgcolor = document.getElementById("hideshow").style.background = "gray";
var fontcolor = document.getElementById("hideshow").style.color = "white";
var text = document.getElementById("hideshow").innerHTML = "Reserved";

localStorage.setItem("hideshow").style.background.value = bgcolor;
localStorage.setItem("hideshow").style.color.value = fontcolor;
localStorage.setItem("hideshow").innerHTML.value = text;

document.getElementById("hideshow").style.background = bgcolor;
document.getElementById("hideshow").style.color = fontcolor;
document.getElementById("hideshow").innerHTML = text;
}

最佳答案

localStorage 只能存储字符串,因此我们的想法是存储要保留的每个按钮的状态。为此,我们可以创建一些简单的函数:

  • 将按钮的状态保存到localStorage
  • 检索加载时每个按钮的状态并设置其状态

// Create a variable storing the buttons
const btns = document.querySelectorAll('.btn');

// Retrieve the button state from localStorage and each
// button's state
const getBtnState = function (btns) {
[].forEach.call(btns, function(btn) {
if (window.localStorage.getItem(btn.id) == 'disabled') {
btn.disabled = true
}
});
};

// Add an event listener to each button to
// disable and store the button's state on click
[].forEach.call(btns, function(btn) {
btn.addEventListener('click', function (e) {
btn.disabled = true
window.localStorage.setItem(btn.id, 'disabled')
})
});

// Call the getBtnState function to set the initial state
// of each button
getBtnState(btns);
<button id="btn1" class="btn">Button 1</button>
<button id="btn2" class="btn">Button 2</button>
<button id="btn3" class="btn">Button 3</button>
<button id="btn4" class="btn">Button 4</button>

由于该演示处于“沙盒”状态,因此该演示无法在 Stackoverflow 上运行。对于工作演示,请前往此 Codepen demo .

关于javascript - 将禁用按钮存储在本地存储中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41419713/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com