表单验证功能异常求助:JS或HTML错误导致提示错位?
Hey there, let's fix that annoying issue where your email error message is showing up under the username field!
问题根源
The bug is in your showError function. When you use document.querySelector('small'), this method only grabs the first <small> element on the entire page. So no matter which input is empty (username or email), you're always updating the small tag under the username field, while the email's small tag stays stuck on its default "Errors" text.
修复方案
Instead of searching the whole document for a small tag, you should look only within the parent .form-control container of the input that has the error. This way, you target the exact small tag that belongs to the problematic input.
Here's the corrected showError function:
function showError(input, message) { const formControl = input.parentElement; formControl.className = 'form-control error'; // 只在当前输入框的父容器内查找对应的small标签 const small = formControl.querySelector('small'); small.innerText = message; }
测试验证
After making this change, try submitting the form with both fields empty:
- The username field will show "username is required" under it
- The email field will show "email is required" under it
This matches the behavior you saw in the tutorial video, since the tutorial was probably targeting the small tag relative to the input's parent container too.
内容的提问来源于stack exchange,提问作者Saral Karki

