I'm writing a plugin and having difficulty getting it to instantiate for multiple elements. I've put [the code] in jsfiddle. specifically the problem is that the call to .each() is probably failing:
$.fn.Image = function (options) {
return this.each(function () {
(new $.Image(this, options));
});
};
I took that from having looked at how other plugins are written but I'm not sure I understand it, particularly why the "new" is used and how when called this results in an array:
var imgs = $('img').Image();
could someone suggest what the right way to do it is?
--开发者_JAVA技巧 Edit --
maybe I'm a little closer. I tried this:
$.fn.Image = function (options) {
var ret = [];
this.each(function () {
ret[ret.length] = $.Image(this, options);
});
return ret;
};
which at least returns an array of objects, but my call:
img.toggle();
fails because what's returned is an array of objects (which can be called with .Image())... so I'm guessing what $.fn.Image() needs to return is a single object which somehow stores its elements... and then how to make all the methods iterate? I don't get it!
Not really sure what you are after, but something like this?
$.fn.Image = function (options) {
$(this).each(function (i,e) {
$.fn.Image(e,options);
});
this.testing = function(a){
if (typeof a == "undefined") a = $(this).text();
alert(a);
return this;
}
return this;
};
var a = $('ul').Image().addClass('working');
a.testing("sss");
$('ul li:first-child').testing().addClass('working');
example: http://jsfiddle.net/niklasvh/wEdzY/
Instead of
return this.each(...)
try
return $(this).each(...)
精彩评论