首页 > 解决方案 > 如何在 3 次尝试使用 javascript 后禁用按钮?

问题描述

3 次尝试后如何禁用提交按钮?这就是所有代码(感谢DCR获得了一些关于 javascript 的帮助)

/*This Script allows people to enter by using a form that asks for a
UserID and Password*/
function pasuser(form) {
if (form.identifier.value=="GG") { 
if (form.pass.value=="123") { 
  window.location('https://www.google.com/');
} else {
alert("Invalid Password");
}

} else {  alert("Invalid UserID");
}
}
<!doctype html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <link rel="stylesheet" href="/style.css">
  <script src="/server.js"></script>
  <title></title>
</head>
<body>
  <div class="box">
    <h2>Login</h2>
    <form>
      <div class="inputBox">
        <input type="text" name="identifier" required="">
        <label>Username</label>
      </div>
      <div class="inputBox">
        <input type="password" name="pass" required="">
        <label>Password</label>
      </div>
      <input type="button" value="Submit" onclick="pasuser(form)">
    </form>
  </div>
</body>
</html>

标签: javascripthtml

解决方案


var trieds = 0;
function pasuser(form) {
    if (form.identifier.value=="GG") {
        if (form.pass.value=="123") {
            window.location = 'https://www.google.com/';
        } else {
            alert("Invalid Password");
            trieds += 1;
        }
    } else {  
        alert("Invalid UserID");
        trieds += 1;
    }
    //Change <input type='button'> for <button>
    document.querySelector("button").disabled = (trieds === 3) ? true : false;
}

推荐阅读