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

JavaScript密码验证函数输出错误,更新后仍异常求修复方案

密码验证函数问题分析与修复

核心问题

你的代码存在一个基础取值错误:

var x = document.getElementById("pw").value;

这里x已经被赋值为输入框的字符串内容,但后续判断里你错误地使用了x.value——字符串类型没有value属性,所以x.value始终是undefined。这直接导致:

  • 输入为空时,undefined === ""不成立,跳过空值判断
  • 无论输入什么内容,undefined !== "1234"永远成立,只会弹出"wrong password"

修复方案

有两种简单的修复方式:

方式1:先获取DOM元素,再读取value

var pw = "1234";

function checkpw(event, input) {
  var x = document.getElementById("pw"); // 先获取输入框DOM元素
  
  if (x.value === "") {
    alert("no password entered");
  } else if (x.value !== pw) {
    alert("wrong password");
  } else {
    alert("correct pw");
  }
}

方式2:直接赋值为value,后续直接用变量判断

var pw = "1234";

function checkpw(event, input) {
  var x = document.getElementById("pw").value; // 直接取输入框的字符串值
  
  if (x === "") { // 直接用变量x判断,无需x.value
    alert("no password entered");
  } else if (x !== pw) {
    alert("wrong password");
  } else {
    alert("correct pw");
  }
}

可选优化

HTML里的空oninput=""可以直接移除;另外如果没有表单包裹,按钮的type="submit"改成type="button"更合理:

<html>
<head>
  <title>Hello</title>
</head>
<body>
  <input type="password" id="pw">
  <button type="button" onclick="checkpw(event, this)">submit</button>
</body>
</html>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 09:30:38