为什么在 jQuery 插件中返回 this.each(function())?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2678185/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 14:02:00  来源:igfitidea点击:

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

jqueryjquery-plugins

提问by Corey Sunwold

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

我看到的一些开发 jQuery 插件的教程和示例往往会返回

this.each(function () {
    //Plugin code here
});

at the end of the function that instantiates the plugin but I have yet to see any reasoning behind it, it just seems to be a standard that everyone follows. Can anyone enlighten me as to the reasoning behind this practice?

在实例化插件的函数的末尾,但我还没有看到它背后的任何推理,它似乎只是每个人都遵循的标准。任何人都可以启发我了解这种做法背后的原因吗?

Edit: For clarification my question was not about why to return this, but rather why the plugin should return this.each.

编辑:为了澄清,我的问题不是关于为什么要返回 this,而是为什么插件应该返回 this.each。

回答by Felix Kling

When you filter elements with a selector ($('.myclass')), it can match more than only one element.
With each, you iterate over all matched elementsand your code is applied to all of them.

当您使用选择器 ( $('.myclass'))过滤元素时,它可以匹配多个元素。
使用each,您可以遍历所有匹配的元素,并将您的代码应用于所有这些元素

回答by gnarf

jQuery supports "chainable methods", which means that mostjQuery functions should return this. .each()returns this, and if you want $('selector').yourPlugin().css(...)to work, you should return this.

jQuery 支持“可链接方法”,这意味着大多数jQuery 函数应该返回this. .each()返回this,如果你想$('selector').yourPlugin().css(...)工作,你应该return this

回答by rubensa

Let me show you two "equivalent" pieces of code that could clarify your question:

让我向您展示可以澄清您的问题的两段“等效”代码:

With jQuery "each" function:

使用jQuery“每个”函数:

(function($) {
    $.fn.mangle = function(options) {
        return this.each(function() {
            $(this).append(' - ' + $(this).data('x'));
        });
    };
})(jQuery);

Without jQuery "each" function:

没有jQuery“每个”函数:

(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, eachfunction is used to apply some code to all elements contained in thisobject (as thisusually refers to a group of elements returned by a jQuery selector) and return the reference to this(as eachfunction always returns that reference -to allow chaining calls-)

因此,基本上,each函数用于施加一些代码的所有元素中包含的this对象(this通常是指一组由一个jQuery选择返回的元素),并返回参照thiseach函数始终返回参考-to允许链接calls-)

As a side note: The second approach (-forloop-) is faster (notably on old browsers) than former one (-eachfunction-).

作为旁注:第二种方法(- forloop-)比前一种方法(- eachfunction-)更快(特别是在旧浏览器上)。

回答by Max Toro

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.

当您编写插件时,您正在扩展 jQuery 对象,并且因为 jQuery 对象是您返回的序列,this.each(function () { });因此您的插件会针对序列中的每个项目执行。

回答by adardesign

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.

简而言之,它允许您利用链接,因为它返回到目前为止已经完成的所有内容,以便下一个.anyMethod()可以对更改/修改的元素进行操作。



Additionally, take a look at these links they will give you a lot of information on jQuery plugin development.



此外,请查看这些链接,它们将为您提供有关 jQuery 插件开发的大量信息。

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

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/

在这里,您有一个不错的基于 Web 的应用程序,可帮助您快速启动 jQuery 插件。 http://starter.pixelgraphics.us/