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

为什么我编写的JavaScript输入验证功能无法正常运行?

问题排查与修正方案

存在的核心问题

  • DOM选择器语法错误:获取msgText和msgTexttwo时混用了id选择器(#)和类选择器(.),.text和.texttwo是类属性,正确选择器应为.text和.texttwo,原写法会返回null,调用classList时直接抛出JS异常,后续逻辑中断。
  • 点击事件默认行为未阻止:触发按钮是<a>标签,href属性为空时点击会默认刷新页面,导致刚执行的验证逻辑被刷新重置,看不到执行效果。
  • 提示文本显示逻辑错误:无论邮箱验证是否通过,都给两个提示文本添加了hide类,错误场景下提示也不会展示,不符合交互预期。
  • 无alert调用逻辑:你提到预期alert函数运行,但当前代码中没有任何调用alert()的语句,自然不会触发弹窗。

修正后代码

const txtName = document.querySelector("#name");
const btnNotify = document.querySelector("#btn-notify");
// 修正类选择器写法
const msgText = document.querySelector(".text");
const msgTexttwo = document.querySelector(".texttwo")
const mailFormat = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;


btnNotify.addEventListener('click', (e) => {
    // 阻止a标签默认跳转刷新行为
    e.preventDefault();
    if(txtName.value.match(mailFormat)  ) {
        // 验证成功隐藏提示
        msgText.classList.add('hide');
        msgTexttwo.classList.add('hide');
        txtName.removeAttribute('style');
        // 验证成功提示弹窗,可按需调整内容
        alert('邮箱验证通过');
    }else {
        // 验证失败显示提示
        msgText.classList.remove('hide');
        msgTexttwo.classList.remove('hide');
        txtName.setAttribute('style', 'border: 2px solid red;');
        // 验证失败提示弹窗,可按需调整内容
        alert('请输入合法的邮箱地址');
    }
});

HTML代码无需调整。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 08:36:03