I have a JQuery 1.4.2 plugin, that uses a set of options. It's pseudo code is like this:
(function($) {
// Shell for the plugin code
$.fn.myPlugIn = function(options) {
// Plugin code
return this.each(function() {
// for each item in selector
options = $.extend($.fn.myPlugIn.defaults, options);
...do stuff
});
$.fn.myPlugIn.defaults = {
header : null,
position : 'absolute',
top : null,
left : null,
forinput : null,
forAnchor : null,
sAjaxSource : null,
onClick : null
};
})(jQuery);
When calling the plugin for several elements on a single page, the options are not unique -- the previous elements options are still in the options.
$(document).ready(function() {
$("#div1").myPlugIn(
{forinput: "input1",
onClick: function(data){
... do stuff
},
});
$("#div2").myPlugIn({
forAnchor: "link1",
onClick: function(data){
... do stuff
},
header: "Parts"
});
});
What am I doing wrong? I expected that each time the plugin was found, it would us开发者_高级运维e the options passed to it. Instead, it uses retains all the options from the first instance and overwrites any re-initialized properties from the second instance.
Any replies are appreciated. Thanks in advance for reading my post.
You need to merge the options into a new object for that instance, like this:
options = $.extend({}, $.fn.myPlugIn.defaults, options);
$.extend()
merges into the first argument all objects passed as parameters after that, so currently they're merging into your $.fn.myPlugIn.defaults
defaults, leaving it tainted for the next use. Instead you want to never mess with the defaults (unless intentionally changing them elsewhere) and merge the options and defaults into another new object.
second thing would be adding 'var options = ...' , omitting var makes it global variable, those setting options to last called attributes.
精彩评论