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

如何使用数组重构表单验证的冗余JavaScript代码?

表单验证JS代码重构方案

重构后的精简代码

"use strict"

// 获取包含输入框和错误图标的所有父容器
const inputContainers = document.querySelectorAll('.first-name-div, .last-name-div, .email-div, .password-div');

inputContainers.forEach(container => {
  const input = container.querySelector('input');
  const errorImg = container.querySelector('.error-img');

  input.addEventListener('blur', () => {
    // 根据输入框内容是否为空,切换错误图标的显示状态
    errorImg.classList.toggle('visible', !input.value.trim());
  });
});

重构思路

  1. 利用DOM结构关联性:输入框和对应错误图标都在同一个父容器中,直接从父容器获取子元素,无需依赖带数字后缀的ID(如error-img1),新增输入项时无需修改JS代码,扩展性更强。
  2. 批量处理元素:用querySelectorAll获取所有目标容器,通过forEach循环统一绑定事件,彻底消除重复逻辑。
  3. 简化状态切换:用classList.toggle替代冗余的if-else判断,第二个参数传入!input.value.trim()作为条件,自动完成类的添加/移除;trim()用于过滤输入前后的空格,避免无效空格被判定为有效内容。

原冗余代码(供对比)

"use strict"

//clunky code for error-img:
const fNameInput = document.getElementById("first-input");
const lNameInput = document.getElementById("last-input");
const emailInput = document.getElementById("email");
const passwordInput = document.getElementById("password");

fNameInput.addEventListener("blur", function(){
    const errorImg1 = document.getElementById("error-img1");
    
    if(!fNameInput.value){
        errorImg1.classList.add("visible");
    } else{
        errorImg1.classList.remove("visible");
    }
});

lNameInput.addEventListener("blur", function(){
    const errorImg2 = document.getElementById("error-img2");

    if(!lNameInput.value){
        errorImg2.classList.add("visible");
    } else{
        errorImg2.classList.remove("visible");
    }
});

emailInput.addEventListener("blur", function(){
    const errorImg3 = document.getElementById("error-img3");

    if(!emailInput.value){
        errorImg3.classList.add("visible");
    } else{
        errorImg3.classList.remove("visible");
    }
});

passwordInput.addEventListener("blur", function(){
    const errorImg4 = document.getElementById("error-img4");

    if(!passwordInput.value){
        errorImg4.classList.add("visible");
    } else{
        errorImg4.classList.remove("visible");
    }
});

原未完成的重构尝试(供对比)

// attempt at making clean code that applies to all inputs:

// const inputs = document.getElementsByTagName("input");
// const errorImgs = document.getElementsByClassName("error-img");

// //learn forEach loop:

// inputs[i].addEventListener("blur", () => {
//     inputs.forEach(element => {
//         if(!element.value){

//         }
//     });
// });

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 21:50:39