繁体   English   中英

按回车键时如何调用 function?

[英]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 truefalse因为它在代码中没有任何意义还阅读了什么是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.

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