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

JavaScript如何在if语句中实现用户输入的3个条件校验?

代码修复说明

核心错误点

  • DOM ID不匹配:HTML中车牌输入框的id为licensed,但JS中使用getElementById("licenseId")获取元素,无法拿到正确的输入值
  • 运算符误用:使用位运算符|替代了逻辑或运算符||,位运算会强制转换数值类型,逻辑完全不符合校验需求
  • 条件语法错误:(secondVal.length == 6) | 7属于无效判断,该表达式结果永远为真值,导致长度校验直接失效
  • 运算符优先级混乱:&&优先级高于||,未对同组判断条件加括号包裹的情况下,执行顺序会完全偏离预期

修正后代码

JavaScript代码

function valForm() {
  // 取值时添加trim()消除首尾空格影响,更符合表单校验常规逻辑
  const firstVal = document.getElementById("nextId").value.trim();
  const secondVal = document.getElementById("licenseId").value.trim();
  // 校验逻辑:Ticket ID不区分大小写匹配MB3804,且车牌长度为6或7
  if (
    firstVal.toUpperCase() === "MB3804" &&
    (secondVal.length === 6 || secondVal.length === 7)
  ) {
    window.location.href = "google.com";
  }
}

HTML代码

<input
    type="text"
    placeholder="License Plate"
    id="licenseId"
    autocomplete="off"
/>
<input
    type="text"
    placeholder="Ticket ID"
    id="nextId"
    autocomplete="off"
/>
<button class="btn btn-primary display-4" type="button" onclick="valForm()">next</button>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 19:15:08