密码输入框内容变更时修改对应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
相关产品推荐
相关产品推荐

