且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

即使刷新后仍然禁用按钮的Javascript

更新时间:2023-01-23 21:02:44

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

You should use cookies. Javascript won't preserve page state after page refresh (unless you are doing server side of course):

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);