如果在子级中定义了错误,则可以将错误附加到输入名称形式,这是常见情况(1).
但是可能会发生错误,该错误是在json对象的根节点中定义的(2).
在这种情况下,应将其附加到formElement上.
以下代码(3)适用于情况(1),但不适用于情况(2).
为了使其在两种情况下均能工作,我应该如何对其进行修改?
附注:我正在使用下划线和jQuery.
(1)
var xhrObj_1 = JSON.parse('{ "children":{"points":{"errors":["This value should not be blank."]},"message":[],"recipient_id":{"errors":["This value should not be blank."]}}}');
(2)
var xhrObj_2 = JSON.parse('{ "errors":["This form should not be …."], "children":{"points":{"errors":["This value should not be blank."]},"message":[],"recipient_id":{"errors":["This value should not be blank."]}}}');
(3)
var parser = function (object) {
_.each(object, function (xhrObject, name) {
console.log(xhrObject)
if (xhrObject.errors) {
var inputElement = element.find('[name="' + name + '"]');
inputElement.closest('.control-group')
.addClass('error');
parserError(xhrObject.errors, inputElement);
} else {
parser(xhrObject); // it is ok for xhrObj_1
// it fails for xhrObj_2
}
});
};
// example with xhrObj_2 which does not work
parser({
"errors": ["errro1"],
"children": {
"points": {
"errors": ["This value should not be blank."]
},
"message": [],
"recipient_id": {
"errors": ["This value should not be blank."]
}
}
});
解决方法:
您应该在顶层开始递归:
var xhr = JSON.parse("…");
(function recurse(obj, name) {
if (obj.errors) {
var inputElement = element.find('[name="' + name + '"]');
inputElement.closest('.control-group').addClass('error');
parserError(obj.errors, inputElement);
}
if ("children" in obj)
for (var prop in obj.children)
recurse(obj.children[prop], prop);
})(xhr, "top");
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。