[英]How can I call a function when I press the enter key?
我正在為我的網站制作密碼。 如何通過按回車鍵而不是按提交按鈕來檢查密碼是否正確? 幫助將不勝感激。
<html>
<script>
function checkPassword() {
var password = document.getElementById("passwordBox");
var passwordText = password.value;
if(passwordText == "password") {
alert("you got it right");
return true;
}
alert("you got it wrong");
return false;
}
</script>
</head>
<body>
<p style="font-size: 30pt;">something</p>
<p>Please enter the password to uh... something </p>
<p>Password: <input id="passwordBox" type="password"/></p>
<button onclick="return checkPassword();">
Submit
</button>
</html>
處理enter
鍵的最簡單方法是將其包裝在表單中並在表單上設置onSubmit
並在按鈕上設置type="submit"
。
這是示例。
<html>
<head>
<script>
function checkPassword() {
var password = document.getElementById("passwordBox");
var passwordText = password.value;
if (passwordText == "password") {
alert("you got it right");
return true;
}
alert("you got it wrong");
return false;
}
</script>
</head>
<body>
<p style="font-size: 30pt">something</p>
<p>Please enter the password to uh... something</p>
<form onsubmit="checkPassword()">
<p>Password: <input id="passwordBox" type="password" /></p>
<button type="submit">Submit</button>
</form>
</body>
</html>
將您的輸入和按鈕包裝在<form>
標記中並使用提交偵聽器您不需要編寫 onclick 並逐個輸入,這將在代碼中大混亂,在按鈕元素 ise type="submit"
這意味着它是form
的一部分,如果您單擊輸入或按鈕,它將執行 function,我還刪除了 return true
和false
因為它在代碼中沒有任何意義還閱讀了什么是e.preventDefult()
const passInput = document.getElementById("passwordBox") const form = document.getElementById("form") form.addEventListener("submit", (e) => { e.preventDefault() var passwordText = passInput.value; if(passwordText == "password") { alert("you got it right"); }else alert("you got it wrong"); })
<p style="font-size: 30pt;">something</p> <p>Please enter the password to uh... something </p> <form id="form"> <p>Password: <input id="passwordBox" type="password" /></p> <button type="submit">Submit</button> </form>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.