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

标签 javascript button refresh

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

<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/

相关文章:

javascript查找可用内存

javascript - 页面顶部的 CSS 菜单

javascript - 从其他 .js 文件访问函数

jquery - 用于切换主体背景图像的 Bootstrap 按钮

Android 无法将 FAB 按钮锚定到 BottomSheet

php - 如何将 setInterval 与 mouseenter 结合起来?

swift - 使用计时器在后台刷新应用程序

javascript - ng build 上 app.module 中的单例服务错误

html - 如何更改 css 以仅影响 id 或 class 而不是 input[type =""]

javascript - Google DFP slotRenderEnded 函数在 pubads().refresh([currentSlot]) 后工作错误