Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/86.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript jquery插件模式中的this和this.each有什么区别?_Javascript_Jquery_Jquery Plugins - Fatal编程技术网

Javascript jquery插件模式中的this和this.each有什么区别?

Javascript jquery插件模式中的this和this.each有什么区别?,javascript,jquery,jquery-plugins,Javascript,Jquery,Jquery Plugins,我正在阅读这个jQuery插件模式:我不明白的是在return语句中调用this上的每个函数的目的是什么?这取代了: ;(function($){ $.fn.extend({ pluginName: function( options ) { this.defaultOptions = {}; var settings = $.extend({}, this.defaultOpti

我正在阅读这个jQuery插件模式:我不明白的是在return语句中调用
this
上的每个函数的目的是什么?这取代了:

    ;(function($){
        $.fn.extend({
            pluginName: function( options ) {

                this.defaultOptions = {};

                var settings = $.extend({}, this.defaultOptions, options);

                return this.each(function() {

                    var $this = $(this);

                });

            }

        });

    })(jQuery);
如果我简单地返回
这个

;(function($){
    $.fn.extend({
        pluginName: function( options ) {

            this.defaultOptions = {};

            var settings = $.extend({}, this.defaultOptions, options);

            return this;

        }

    });

})(jQuery);
两者的工作原理相同。据我所知,
充当插件中的选定元素。例如,如果我有三个类为
test
的div,我会:

$(".test").pluginName(); // returns an array of three div elements in both plugin styles  
据我所知,
$(“.test”)
给出了一个由三个dom元素组成的数组,并且为
$(“.test”).pluginName()调用了三次pluginName
和三个返回值被推送到一个数组中,该数组最后被返回

所以请解释为什么他们在返回语句中使用
this.each()
而不是
this

据我所知,$(“.test”)给出了一个包含三个dom元素的数组,并且为$(“.test”).pluginName()调用了三次pluginName;三个返回值被推送到一个数组中,最后返回


这是不对的
pluginName()
只调用一次,将其设置为与三个DOM元素对应的jQuery对象。因此,使用
this.each()
可以循环jQuery对象,并为每个对象执行任何需要执行的操作。

正如js文件名所示,这只是一个构建框架。当然,如果对每个元素都不做任何事情,那么就不需要
.each()
。但如果无事可做,这将成为一个非常无趣的插件。如果需要对集合中的每个项目执行不同的操作,请使用
.each()
。@epascarello您能用一些例子解释一下吗?例如,如果我只想提醒那些具有
pop
类的
.test
,那么我会使用
this。每个
作为回报吗?
该上下文中的该
是一个集合。您可以像使用任何其他jquery集合一样使用它。您可以使用.each、.map、.attr、.html、.whateverjqeurymethodorpluginyouwant或根本不使用。this.each()
就像
$(.foo”)。each()
,您知道在这种情况下为什么要使用each()吗?