[英]Javascript closure issue on click event
我已经浏览了有关“关闭”问题的许多答案,但是无法解决我的特定问题。
以下js代码获取一个json文件并将其存储,然后根据数据进行某种形式的验证。
问题在于表单的提交和validate函数的执行,我应该看到两个错误,但是我只得到最后一个字段的错误(记录在控制台中)。
这是一个很明显的关闭问题,但是整天花在上面我还是无法解决。 下面是代码,click事件在底部...
我目前仅检查最小长度规则。
// Get the json file and store
function loadJSON(callback) {
var xobj = new XMLHttpRequest();
xobj.overrideMimeType("application/json");
xobj.open('GET', 'js/rules.json');
xobj.onreadystatechange = function () {
if (xobj.readyState == 4 && xobj.status == "200") {
// Required use of an anonymous callback as .open will NOT return a value but simply returns undefined in asynchronous mode
callback(xobj.responseText);
}
};
xobj.send(null);
}
// Load json...
loadJSON(response);
// Create global vars...
var lookup = [], errors = [], i, e, id, lookupId, minLength;
function response(responseData) {
// Create objects from json data
var rulesSet = JSON.parse(responseData);
// Loop through objects
for (i = 0; i < rulesSet.length; i++) {
// Create a lookup for each object that can be used later
lookup[rulesSet[i].id] = rulesSet[i];
}
// Loop through form elements and store id's
// Validate the form
function validate(e) {
var elements = document.getElementsByTagName('input');
for (e = 0; e < elements.length; e++) {
id = elements[e].getAttribute('id');
lookupId = lookup[id].rules; var rules;
// Loop through rules of the matched ID's
for (rules of lookupId){
// Check if there is a min length rule
if(rules.name === 'min_length') {
minLength = rules.value.toString();
// Check if the rule is valid (is a number)
if(isNaN(minLength) || minLength.length === 0){
// Log an error somewhere here
// Run the minLength function and report an error if it fails validation
} else if(!checkMinLength(minLength, id)) {
errors[errors.length] = id + " - You must enter more than " + minLength + " characters";
}
}
}
// If there are errors, report them
if (errors.length > 0) {
reportErrors(errors);
//e.preventDefault();
}
}
}
validate();
// Check the length of the field
function checkMinLength(minLength, id){
var val = document.getElementById(id).value;
if(val < minLength){
return false;
}
return true;
}
// Error reporting
function reportErrors(errors){
for (var i=0; i<errors.length; i++) {
var msg = errors[i];
}
console.log(msg);
}
$('#email-submit').on('click',function(e){
validate(e);
});
}
可能不相关,但下面是已加载的json ...
[
{
"id": "search",
"rules": [
{
"name": "min_length",
"value": "5"
},
{
"name": "email"
}
]
},
{
"id": "phone-number",
"rules": [
{
"name": "min_length",
"value": 8
}
]
},
{
"id": "surname",
"rules": [
{
"name": "min_length",
"value": 10
}
]
}
]
以及验证的基本形式...
<form action="index.html" name="searchForm" id="search-form">
<label for="search">Email</label>
<input type="text" id="search" name="email" placeholder="Enter email">
<input type="text" id="phone-number" name="name" placeholder="Enter name">
<button type="submit" id="email-submit">Submit</button>
</form>
该代码完全按照您的要求执行
// Error reporting
function reportErrors(errors){
for (var i=0; i<errors.length; i++) {
var msg = errors[i]; <-- setting the variable on each iteration
}
console.log(msg); <-- reads the last value from the last iteration
}
您需要将控制台移至for循环中
// Error reporting
function reportErrors(errors){
for (var i=0; i<errors.length; i++) {
var msg = errors[i];
console.log(msg);
}
}
甚至不循环
// Error reporting
function reportErrors(errors){
console.log(errors.join("\n"));
}
现在是逻辑问题,您需要在for循环中声明一个函数
function response(responseData) {
// ignored code //
var elements = document.getElementsByTagName('input');
for (e = 0; e < elements.length; e++) {
function validate(e) { <-- THIS SHOULD NOT BE IN THE FOR LOOP
同样,就像错误消息一样,只有最后一个要在那里...
创建更易读的方案而不关闭。
var submitButton = document.querySelector('#email-submit')
function validate (evt) {
async function loadRules (url) {
var rawData = await fetch(url)
return await rawData.json()
}
function reportErrors (error) {
evt.preventDefault()
// Report logic here
}
function evaluate (rules) {
// Your validate rules here
// loaded rules in rules object
// eg. rules[0]['rules'].name
}
loadRules('js/rules.json').then(evaluate)
}
submitButton.addEventLister('click', validate)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.