[英]Simple JavaScript password checker won't loop after the first iteration
至少,我認為迭代在第一個循環之后停止。 在發送錯誤消息之前輸入錯誤密碼時,我試圖讓我的密碼循環 3 次。 當我輸入一個錯誤的密碼並單擊我的提交按鈕時,迭代停止。 編碼新手,所以如果我做錯了什么,請告訴我。
我的 JS(按鈕on-click
功能):
var password = "password";
var notif = document.getElementById("notif");
var entryCount = 0;
var entryLimit = 3;
var error = false;
function inputPW(){
for(i = 0; i < 3; i++){
notif.innerHTML = "";
if(passwordInp.value === password){
notif.innerHTML = "You got it!";
break;
}
else if(i < 3){
notif.innerHTML = "Incorrect password. Please try again.";
}
else{
notif.innerHTML = "Password limits exceeded.";
}
}
}
我的 HTML(僅正文):
<h1>Password Getter</h1>
<p>Password:</p>
<input id = "passwordInp" type="text" placeholder="Password" autofocus>
<button id="enterBtn" type="button" onclick="inputPW()">Submit</button>
<p id="notif"></p>
<script src="JSscript.js"></script>
for 循環一次運行相同的代碼,而不是等待用戶的輸入。 由於輸入在運行時沒有改變,它只運行一次。 而是在用戶單擊提交按鈕並增加全局變量時調用該函數。
var password = "password"; var notif = document.getElementById("notif"); var passwordInp = document.getElementById("passwordInp"); var entryCount = 0; var entryLimit = 3; var error = false; var i = 0; function inputPW(){ notif.innerHTML = ""; if(passwordInp.value === password){ notif.innerHTML = "You got it!"; break; else if(i < 3){ notif.innerHTML = "Incorrect password. Please try again."; } else{ notif.innerHTML = "Password limits exceeded."; } } }
//these constants won't change during execution
const LIMIT = 3;
const PASSWORD = 'password';
let entryCount = 0; // a global variable
let authorized = true; //can we still try?
function handleInput(inp){
if(!authorized){
return; //we do nothing if we're not authorized anymore
}
const matches = inp == PASSWORD;
if(matches){
//do 'success' thing
} else if(entryCount < LIMIT){
entryCount++;
//do 'not success' thing
} else{
authorized = false;
//do 'unauthorized' thing
}
}
<h1>Password Getter</h1>
<p>Password:</p>
<input id = "passwordInp" type="text" placeholder="Password" autofocus>
<button id="enterBtn" type="button" onclick="handleClick(passwordInp.value)">Submit</button>
<p id="notif"></p>
<script src="JSscript.js"></script>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.