至少,我認為迭代在第一個回圈之后停止。在發送錯誤訊息之前輸入錯誤密碼時,我試圖讓我的密碼回圈 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>
uj5u.com熱心網友回復:
//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>
uj5u.com熱心網友回復:
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.";
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/476070.html
標籤:javascript html for循环 密码
