插件在被调用时抛出 ReferenceError

Plugin throws ReferenceError when being called

我写了一个非常基本的插件,它在模糊事件中被调用,我把它和另一个我写的工作正常的文件放在一个文件中。 当我离开一个输入字段时,我一直收到一个错误,说它未定义,我不确定为什么它一直这么说。

错误:

Uncaught ReferenceError: Validation_Required is not defined

我的插件是

(function ($) {

    // This one works fine, but is called on a button click
    $.fn.Validation = function (options)...

    // This is the plugin that throws the ReferenceError
    $.fn.Validation_Required = function (e) {
        let me = $('#' + e.target.id);

        if (me[0].value.length > 0) {
            me.css('border', '2px solid green');
        }
        else {
            me.css('border', '2px solid red');
        }
        return;
    }
}(jQuery));

函数的调用是

$('.required').blur((e) => {
        Validation_Required(e);
});

为什么会抛出错误?

您的问题在这一行:

Validation_Required(e);

更改为:

$(this).Validation_Required(e);

Validation_Required不是全局函数而是jQuery中新增的方法。因此,您需要一个 jQuery 对象才能使用该功能。

(function ($) {

    // This one works fine, but is called on a button click
    $.fn.Validation = function (options) {
    }

    // This is the plugin that throws the ReferenceError
    $.fn.Validation_Required = function (e) {
        console.log('Validation_Required called....');
        return;
        let me = $('#' + e.target.id);

        if (me[0].value.length > 0) {
            me.css('border', '2px solid green');
        }
        else {
            me.css('border', '2px solid red');
        }
        return;
    }
}(jQuery));


$('.required').blur(function (e) {
    $(this).Validation_Required(e);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<input class="required" type="text">