【问题标题】:Uncaught TypeError: Cannot set property 'foreground' of undefined未捕获的类型错误:无法设置未定义的属性“前景”
【发布时间】:2020-07-06 19:34:15
【问题描述】:

这是我的基本 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();

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

【问题讨论】:

  • 没有称为前景的 CSS 样式属性。使用样式“颜色”代替前景
  • 请澄清问题。说明你最终想要达到的目标。

标签: jquery


【解决方案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,传入options:

$(".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>

【讨论】:

  • 在 IIFE 之外不会有范围问题吗?
  • @mplungjan - 如果$ = jQuery 在 IIFE 之外(通常但并非总是如此),则不会。什么似乎超出了范围?
  • @max - 对我有用,我在答案中添加了一个活生生的例子。
  • 是的,你是对的,终于代码可以正常工作了,非常感谢......
猜你喜欢
  • 2015-06-24
  • 1970-01-01
  • 2022-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-30
  • 2011-03-11
相关资源
最近更新 更多