我在该代码中看到了几个问题:
- 在一个地方你正在使用
$.fn.myPlugin.defaults(复数),在另外两个地方你正在使用$.fn.myPlugin.default(单数)。
- 您创建
$.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>