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

无法通过函数修改DOM求助:JS表单验证样式设置无效

问题解决:JS表单验证中设置display无效的问题

你的代码里有三个关键问题,导致设置display没反应:

  1. 未定义pwForm变量:HTML里表单的id是passwordForm,但你直接用pwForm没有获取这个元素,JS根本不知道它指向什么。
  2. 设置样式的语法错误:正确修改元素display属性的写法是元素.style.display = "none",你写的pwForm.display.style完全不符合JS语法。
  3. 表单默认提交会刷新页面:即使你改了样式,表单提交后页面会刷新,瞬间恢复原样,必须阻止这个默认行为。

修正后的完整代码如下:

JS代码

function validate(event) {
  // 阻止表单默认提交刷新页面的行为
  event.preventDefault();
  let x = document.forms["myForm"]["fname"].value;
  // 获取目标表单元素
  const pwForm = document.getElementById("passwordForm");
  if (x == "14") {
    // 正确设置display属性隐藏表单
    pwForm.style.display = "none";
  }
}

HTML代码

<form name="myForm" onsubmit="validate(event)" id="passwordForm">
  <input
    id="passwordPrompt"
    type="text"
    placeholder="how many years?"
    name="fname"
  />
  <input type="submit" value="Submit" />
</form>

现在输入14点击提交,表单就会被隐藏,且不会刷新页面。

内容的提问来源于stack exchange,提问作者mr. baby

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 19:05:54