如何使用新对象扩展$ .fn

时间:2014-04-07 13:25:42

标签: javascript jquery

我有以下jquery-function:

(function($) {
    $.fn.formCheck = function(options) {
        var form = this;  var errorList = [];
        var settings = {
             errorClass: "error",
             focusInvalid: true,
             errorContainer: $([])
        }

        // Extend the options so they work with the plugin
        if(options) {
            $.extend(settings, options);
        }

         var fc = {
              messages: {
                required: "Dieses Feld ist ein Pflichtfeld.",
                remote: "Please fix this field.",
                email: "Geben Sie bitte eine gültige E-Mail Adresse ein.",
             }
          }
    }
})(jQuery);

现在我想用以下代码扩展它们:

(function($) {
    $.extend(formCheck.fc.messages, {
          required: "This field is required.",
          remote: "Please fix this field.",
          email: "Please enter a valid email address.",
    });
}(jQuery));

我收到消息ReferenceError:未定义formCheck。

怎么了?

我制作了一个新的jsfiddle:new fiddle

2 个答案:

答案 0 :(得分:0)

您需要全局化您的选项(通过插件使其可以访问任何其他配置)。例如:

(function($){
    $.fn.coloredTextOptions = {
        color: 'blue'
    };
    $.fn.coloredText = function(options){
        var opts = $.extend({}, $.fn.coloredTextOptions, options);
        return this.css('color', opts.color);
    };
})(jQuery);

$('p').coloredText(); // text is blue (as was set initially)

(function($){
    $.extend($.fn.coloredTextOptions, {
        color: 'red'
    });
})(jQuery);

$('p').coloredText(); // text is red (as modified by extend)

$('p').coloredText({ color: 'green' }); // text is green
                                        // (as overridden by passed options)

http://jsfiddle.net/8f7La/

答案 1 :(得分:0)

您已扩展jQuery的fn媒体资源,以包含您的formCheck功能。但是在你下面试图像这样访问它

formCheck.fc.messages

您的函数formCheck存在于名为fn的属性中,该属性位于jQuery对象中。您必须像$.fn.formCheck$.fn['formCheck']一样访问它。

其次,我们假设您决定以此方式声明您的功能。

   (function () {
       var formCheck = function () {
           // Code
       }
   })();

   formCheck(); // ReferenceError. Not defined

由于您已将其包装在匿名函数中,因此在该范围之外不可见。您需要将其暴露到更高级别的范围,以便上述工作。

   (function () {
       var formCheck = function () {
           // Code
       }

       window.formCheck = formCheck;
   })();

   formCheck(); // This works. Equivalent to calling `window.formCheck();`

您遇到错误的另一件事是尝试访问您的函数的私有变量fc,就好像它是属性一样。 我建议你阅读这篇文章How to call a method inside a jquery function from global scope?