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

密码输入框内容变更时修改对应label文字颜色的事件绑定问题

修复方案

存在的错误点

  • 选择器语法错误:querySelector查找ID元素需要加#前缀,你写的querySelector("password")应该改为querySelector("#password"),查找pw元素同理要写#pw
  • 方法名拼写错误:事件绑定方法是小写开头的addEventListener,不是大写开头的AddEventListener
  • 事件名错误:事件名统一为小写,Change要改为change,如果需要输入实时触发推荐用input事件(change事件仅在输入框失焦时触发)
  • 语法错误:if判断语句括号不匹配,且JS中布尔值为小写true,你写的if (checkpw(...)) == True) 存在多余右括号,且True要改为true
  • 多余闭合括号:事件回调函数末尾多写了一个},导致语法报错
  • 校验函数方法调用错误:JS中获取字符串长度用.length属性,没有.len()方法,what.len()要改为what.length
  • 事件绑定对象错误:你尝试给id=pw的label绑定事件是无效的,事件需要绑定到密码输入框元素上

修复后完整代码

DOM结构

<label for="password" id="pw">Password:</label> 
<input type="password" name="password" id="password">

JS代码

// 密码校验函数
function checkpw(what) {
    let sm = 0;
    let lg = 0;
    let num = 0;
    let sym = 0;
    for (let i = 0; i < what.length; i++) {
        const vchr = what.charCodeAt(i);
        if (vchr > 40 && vchr < 127) {
            if (vchr > 47 && vchr < 58) {
                num = 1;
            } else if (vchr > 64 && vchr < 91) {
                lg = 1;
            } else if (vchr > 96 && vchr < 123) {
                sm = 1;
            } else {
                sym = 1;
            }
        }
    }
    return sm && lg && num && sym;
}

// 绑定输入事件
const passwordInput = document.querySelector("#password");
const pwLabel = document.querySelector("#pw");
passwordInput.addEventListener("input", function() {
    if (checkpw(passwordInput.value)) {
        pwLabel.style.color = "#00ff00";
    } else {
        pwLabel.style.color = "#ff0000";
    }
});

内容的提问来源于stack exchange,提问作者Jeff Springs

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 16:15:04