如何让含input事件监听的main函数同步执行并输出有效输入值?
问题描述
我有一个名为main的函数,在该函数中通过input事件监听器校验用户输入。当输入有效时,我尝试将输入值返回给main函数,但调用console.log(main())时却输出undefined。请问如何实现每次用户输入有效值时都能输出该值,同时解决当前返回undefined的问题?
原代码
HTML代码
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Demo Code</title> </head> <body> <form action="" method="get"> <input type="text" name="name" id="name" placeholder="Enter Your Name"> <label id="error"></label> </form> </body> </html>
(注:原HTML存在重复<body>标签,已修正)
JavaScript代码
function validator(regex, input) { /*This function takes regex and user input and returns true or false*/ const re = regex; return re.test(input); } function main() { const inputName = document.querySelector('#name'); const errorName = document.querySelector('#error'); inputName.addEventListener('input', () => { // regular expression string only alphabets and no space isValid = validator(/^[a-z]*$/, inputName.value); if (isValid) { errorName.innerHTML = "Valid Name"; // it should only returns when isValid is true, // as later I want to use correct inputName.value in some another function return inputName.value; } else { errorName.innerHTML = "Invalid Name"; } }); } let name = main() console.log(name) // I want to console.log the value every time when inputName value returns the correct name, but in this case it prints undefined
问题原因
main函数本身没有返回语句,调用main()自然返回undefined;- 事件回调里的
return是回调函数的返回值,不会传递给main——输入事件是异步触发的,用户输入行为发生在main执行完成之后,不可能让main同步返回未来才会产生的输入值。
解决方案
既然输入事件是异步的,我们不需要让main同步返回值,直接在事件回调中处理有效输入的逻辑即可:
- 输入有效时直接执行
console.log输出值; - 若后续需要将值传给其他函数,可在此处直接调用目标函数并传入值。
修改后的JavaScript代码如下:
function validator(regex, input) { const re = regex; return re.test(input); } function main() { const inputName = document.querySelector('#name'); const errorName = document.querySelector('#error'); inputName.addEventListener('input', () => { // 声明局部变量避免污染全局作用域 const isValid = validator(/^[a-z]+$/, inputName.value.trim()); if (isValid) { const validValue = inputName.value; errorName.textContent = "Valid Name"; // 用textContent替代innerHTML更安全 console.log(validValue); // 若需传给其他函数,直接在此处调用 // otherFunction(validValue); } else { errorName.textContent = "Invalid Name"; } }); } // 直接调用main初始化事件监听 main();
关键修改点
- 移除无效的
let name = main()赋值,直接调用main()初始化监听; - 在输入有效时直接执行
console.log输出值,同时支持调用其他函数处理该值; - 修复
isValid未声明导致的全局变量问题; - 用
textContent替代innerHTML,避免XSS风险; - 修改正则为
^[a-z]+$,避免空字符串被判定为有效。
内容的提问来源于stack exchange,提问作者abhishek surela
相关产品推荐
相关产品推荐

