Some of the tutorials and examples I have seen for developing jQuery plugins tend to return
this.each(function () {
//Plugin code here
});
jQuery supports "chainable methods", which means that most jQuery functions should return this
. .each() returns this
, and if you want $('selector').yourPlugin().css(...)
to work, you should return this
.
When you write a plugin you are extending the jQuery object, and because the jQuery object is a sequence you return this.each(function () { });
so that your plugin is executed for each item of the sequence.
In short it allows you to take advantage of chaining, since it returns everything that has been done till now so the next .anyMethod()
can act upon the changed/modified elements.
Additionally, take a look at these links they will give you a lot of information on jQuery plugin development.
http://www.webresourcesdepot.com/jquery-plugin-development-10-tutorials-to-get-started/
http://www.learningjquery.com/2007/10/a-plugin-development-pattern
http://snook.ca/archives/javascript/jquery_plugin
And here you have a nice web based app that helps you jump start your jQuery plugins. http://starter.pixelgraphics.us/
When you filter elements with a selector ($('.myclass')
), it can match more than only one element.
With each
, you iterate over all matched elements and your code is applied to all of them.
Let me show you two "equivalent" pieces of code that could clarify your question:
With jQuery "each" function:
(function($) {
$.fn.mangle = function(options) {
return this.each(function() {
$(this).append(' - ' + $(this).data('x'));
});
};
})(jQuery);
Without jQuery "each" function:
(function($) {
$.fn.mangle = function(options) {
var objs = this;
for (var i=0; i<objs.length; i++) {
var obj = objs[i];
$(obj).append(' - ' + $(obj).data('x'));
};
return this;
};
})(jQuery);
So, basically, each
function is used to apply some code to all elements contained in this
object (as this
usually refers to a group of elements returned by a jQuery selector) and return the reference to this
(as each
function always returns that reference -to allow chaining calls-)
As a side note: The second approach (-for
loop-) is faster (notably on old browsers) than former one (-each
function-).