我的反应应用程序中有表单,它通过jquery验证插件进行验证。
let validator = $('form').validate({
errorClass: 'has-error',
errorElement:'label',
});
validator.form();
if ($('.has-error').length > 0) {
$('.has-error').each(function (index) {
$.validator().showErrors({prop:$(this).data('error')});
});
} else {
/*work with data*/
}
所有错误消息都显示正常,但每次触发验证时,我在控制台中收到错误:
this.init is not a function
并将我链接到插件脚本中的代码:
$.validator = function( options, form ) {
this.settings = $.extend( true, {}, $.validator.defaults, options );
this.currentForm = form;
this.init();
};
我该如何解决它?UPD 1:在下面的插件脚本代码中,我找到了这段代码:
$.extend( $.validator, {
//some code
prototype: {
init: function() {
this.labelContainer = $( this.settings.errorLabelContainer );
this.errorContext = this.labelContainer.length && this.labelContainer || $( this.currentForm );
this.containers = $( this.settings.errorContainer ).add( this.settings.errorLabelContainer );
this.submitted = {};
this.valueCache = {};
this.pendingRequest = 0;
this.pending = {};
this.invalid = {};
this.reset();
//some code
也许它因为这个 init 函数而触发错误异常?
我认为问题出在这一行:
$.validator().showErrors({prop:$(this).data('error')});
$.validator
函数是一个构造函数,因此它必须始终与new
关键字一起使用。如果您将其称为普通函数this
则此函数内部指向全局window
(或在strict mode
中undefined
(,该函数没有init
方法