gpt4 book ai didi

即使刷新后也能保持按钮禁用的 JavaScript

转载 作者:行者123 更新时间:2023-11-28 19:57:32 26 4
gpt4 key购买 nike

我有一个按钮,当您单击它时,它会被禁用,但当我刷新页面时,它仍然应该被禁用。我怎样才能做到这一点?

<button onclick="this.disabled = true">Disable</button>

最佳答案

您应该使用cookies 。页面刷新后,Javascript 不会保留页面状态(当然,除非您在服务器端进行):

DEMO

代码:

function setCookie(name, value){
// Set cookie to `namevalue;`
// Won't overwrite existing values with different names
document.cookie = name + value + ';';
}

function checkIfClicked(){
// Split by `;`
var cookie = document.cookie.split(";");

// iterate over cookie array
for(var i = 0; i < cookie.length; i++){
var c = cookie[i];
// if it contains string "click"
if(/click/.test(c))
return true;
}
// cookie does not exist
return false;
}

// Set clicked to either the existing cookie or false
var clicked = checkIfClicked();

// Check if it was clicked before
alert(clicked);

// Get the button
var button = document.getElementsByTagName("button")[0];

// If it had been clicked, diable button
if (clicked) button.disabled = true;

// Add event listener
// When button clicked, set `click` cookie to true
// and disable button
button.addEventListener("click", function(){
setCookie("click", "true");
button.disabled = true;
}, false);

关于即使刷新后也能保持按钮禁用的 JavaScript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22279372/

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