0

这是我的基本 jquery 插件代码,应用此代码后出现错误

未捕获的类型错误:无法设置未定义的属性“前景”

(function($){

    $.fn.myPlugin = function(options){

        var settings = $.extend({}, $.fn.myPlugin.default, options);

        $.fn.myPlugin.default = {
            foreground: "red",
            background: "green"
        };
    }

}(jQuery));

在这里我试图使用这个插件代码访问它

    $.fn.myPlugin.default.foreground = "blue";

    $(".testDemo").myPlugin();

有没有人可以帮我解决这个问题!请提出要求

4

1 回答 1

1

我在该代码中看到了几个问题:

  1. 在一个地方你正在使用$.fn.myPlugin.defaults(复数),在另外两个地方你正在使用$.fn.myPlugin.default(单数)。
  2. 您创建$.fn.myPlugin.default对象的代码您的插件函数中(并且您的代码尝试使用它之后)。

导致您遇到的特定错误是#2,因为当您使用插件时,此行会尝试使用不存在的东西:

$.fn.myPlugin.default.foreground = "blue";

在设置插件时,您应该在插件函数之外创建一次defaults/default对象。

像这样的东西:

(function($){
    $.fn.myPlugin = function(options){
        var settings = $.extend({}, $.fn.myPlugin.defaults, options);
        // ...do the plugin's work here, typically inside a `this.each(/*...*/);` callback, and return `this`
    };

    $.fn.myPlugin.defaults = {
        foreground: "red",
        background: "green"
    };
}(jQuery));

然后使用它,不要写入defaults,传入选项:

$(".testDemo").myPlugin({foreground: "blue"});

现场示例:

(function($){
    $.fn.myPlugin = function(options){
        var settings = $.extend({}, $.fn.myPlugin.defaults, options);
        // ...do the plugin's work here, typically inside a `this.each(/*...*/);` callback, and return `this`
        return this.each(function() {
            $(this).css({
                color: settings.foreground,
                backgroundColor: settings.background
            });
        });
    };

    $.fn.myPlugin.defaults = {
        foreground: "red",
        background: "green"
    };
}(jQuery));

$(".testDemo").myPlugin({
    foreground: "blue",
    background: "#ddd"
});
<div class="testDemo">This is a .testDemo element</div>
<div class="testDemo">This is another .testDemo element</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

于 2020-03-26T07:40:05.257 回答