【问题标题】:Plugin throws ReferenceError when being called插件在被调用时抛出 ReferenceError
【发布时间】:2018-09-15 14:04:41
【问题描述】:

我写了一个非常基本的插件,它在模糊事件上被调用,我把它和我写的另一个文件放在一个文件中,效果很好。 当我离开输入字段时,我不断收到一条错误消息,说它未定义,我不确定它为什么一直这样说。

错误:

未捕获的 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);
});

为什么会抛出错误?

【问题讨论】:

    标签: jquery jquery-plugins


    【解决方案1】:

    您的问题在这一行:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-05-04
      • 1970-01-01
      • 2022-06-11
      • 2019-06-03
      • 1970-01-01
      • 2018-10-26
      • 2016-11-22
      • 2014-07-31
      相关资源
      最近更新 更多