You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在按下回车键时调用函数?网页密码校验场景实现方案

解决方案

方案1(推荐:原生表单适配)

利用HTML表单默认支持回车提交的特性实现,无需额外监听键盘事件,兼容性更好,修改步骤如下:

  • 用<form>标签包裹密码输入框和提交按钮
  • 绑定表单的submit事件,先阻止默认提交跳转,再调用校验函数
  • 原有校验逻辑无需改动

修改后的完整代码:

<html>
 <head>
 <script>
  function checkPassword() {
   var password = document.getElementById("passwordBox");
   var passwordText = password.value;
   if(passwordText == "password") {
    alert("密码正确");
    return true;
   }
   alert("密码错误");
   return false;
   }
 </script>
</head>
<body>
 <p style="font-size: 30pt;">站点内容</p>
 <p>请输入密码访问对应内容</p>
 <form onsubmit="event.preventDefault(); checkPassword();">
  <p>密码:<input id="passwordBox" type="password"/></p>
  <button type="submit">提交</button>
 </form>
</body>
</html>

方案2(单独监听键盘事件)

如果不想改动现有结构,直接给密码输入框添加回车事件监听即可,只要修改input标签的属性:

<input id="passwordBox" type="password" onkeydown="if(event.key === 'Enter') checkPassword()"/>

内容的提问来源于stack exchange,提问作者embers02

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 10:24:07