我制作了一个 jQuery 插件,它运行得非常好。但当我在同一页面上有多个实例时,最后一个实例的选项/设置将用于两者。
这是它的精简版本...对于篇幅抱歉。
(function() {
var settings = {};
var defaults = {
duration : 1000,
easingShow : 'easeOutBounce',
easingHide : 'easeOutQuad'
};
var methods = {
init : function(options) {
return this.each(function(n) {
settings = $.extend(defaults, options);
});
},
show : function() {
// settings used here
},
hide : function() {
// also used here
}
};
$.fn.expander = function(method) {
if (methods[method]) {
return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
} else if (typeof method === 'object' || !method) {
return methods.init.apply(this, arguments);
} else {
$.error('Method ' + method + ' does not exist on jQuery.expander');
}
};
})(jQuery);
我确信这是某种命名空间问题,因为我经常对此感到困惑。
谢谢
最佳答案
使用
settings = $.extend(true, {}, defaults, options);
来自 jquery 文档 @ http://api.jquery.com/jQuery.extend/
deep If true, the merge becomes recursive (aka. deep copy). target The object to extend. It will receive the new properties. object1 An object containing additional properties to merge in. objectN Additional objects containing properties to merge in.
Keep in mind that the target object (first argument) will be modified, and will also be returned from $.extend(). If, however, we want to preserve both of the original objects, we can do so by passing an empty object as the target.
要为每个元素设置不同的设置,您可以使用 .data() 将它们存储在每个元素中
关于具有默认和多个实例的 jquery 设置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6155172/