Why return this.each(function()) in jQuery plugins?

后端 未结 5 2093
感情败类
感情败类 2020-12-01 02:00

Some of the tutorials and examples I have seen for developing jQuery plugins tend to return

this.each(function () {
    //Plugin code here
});
5条回答
  •  自闭症患者
    2020-12-01 02:30

    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

    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-).

提交回复
热议问题