【发布时间】:2023-01-13 02:25:05
【问题描述】:
我有一个名为main 的函数,我在其中调用输入事件侦听器并检查用户是否输入了有效输入。如果输入正确,我会将输入值返回给主函数。但是,当我尝试 console.log 值时,它返回为 undefined。我怎样才能让这个函数同步工作以达到预期的结果,同时还要注意每次用户输入正确的值时我都想 console.log 输入值?
[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>
<body>
<form action="" method="get">
<input type="text" name="name" id="name" placeholder="Enter Your Name">
<label id="error"></label>
</form>
</body>
</html>
[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
【问题讨论】:
标签: javascript