繁体   English   中英

使用 javascript 尝试 3 次后如何禁用按钮?

[英]How do I disable a button after 3 tries with 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>

一种方法是添加一个计数器并在计数器达到 3 并且凭据仍然错误时隐藏/删除按钮。

但是,在服务器端执行此操作要安全得多!!!

以下是基于您的代码的 JavaScript 客户端解决方案,但同样,仅在客户端进行检查是不安全的。

 /*This Script allows people to enter by using a form that asks for a UserID and Password*/ var button = document.getElementById("submitBtn"); var attempts = 0; function pasuser(form) { attempts++; if (form.identifier.value=="GG") { if (form.pass.value=="123") { attempts = 0; window.location('https://www.google.com/'); } else { alert("Invalid Password"); button.style.display = attempts === 3 ? "none" : "block"; } } else { alert("Invalid UserID"); button.style.display = attempts === 3 ? "none" : "block"; } }
 <!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 id="submitBtn" type="button" value="Submit" onclick="pasuser(form)"> </form> </div> </body> </html>

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM