插件在被调用时抛出ReferenceError

时间:2018-09-15 14:04:42

标签: jquery jquery-plugins

我写了一个非常基本的插件,该插件在模糊事件中被调用,并将其与我编写的另一个可以正常工作的文件放在一起。 当我离开输入字段时,我总是收到错误消息,说它是未定义的,而且我不确定为什么它总是这么说。

错误:

  

未捕获的ReferenceError:未定义Validation_Required

我的插件是

(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);
});

为什么会引发错误?

1 个答案:

答案 0 :(得分:0)

您的问题在这一行:

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">