own variables for each element (jQuery plugin)
I'm trying to understand, how jQuery plugins work. This is my first test plugin (it does nothing :) )
(function($)
{
var methods =
{
init : function(options)
{
if (options) $.extend(settings, options);
myElement = $(this);
return myElement;
},
getInfo : function()
{
console.log('Info = ' + myElement.attr('id') + ' [' + settings.itemName + ']');
}
};
var setting开发者_运维技巧s = {'itemName' : 'item' };
var myElement = null;
$.fn.myTest = 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.myTag');
}
};
})(jQuery);
In my HTML page I call it:
$(document).ready(function()
{
t = $('#list').myTest({itemName:'First'});
t.myTest('getInfo');
t2 = $('#l2').myTest({itemName:'Hello World'});
t2.myTest('getInfo');
t.myTest('getInfo');
});
And I see, that plugin's variable 'myElement' was changed:
Info = list [First] - OK
Info = l2 [Hello World] - OK
Info = l2 [Hello World] - Why???
What I need to write, that plugin variable 'myElement' was different for each element? Thanks.
I solved. Thanks.
data = $this.data('test');
if (!data)
{
$(this).data('test',
{
element : $this,
settings : settings
});
}
精彩评论