【问题标题】:What is the difference between this and this.each in jquery plugin pattern?jquery插件模式中this和this.each有什么区别?
【发布时间】:2017-03-22 18:31:43
【问题描述】:

我正在阅读这个 jQuery 插件模式:https://github.com/jquery-boilerplate/jquery-patterns/blob/master/patterns/jquery.extend-skeleton.js 我不明白的是,在 return 语句中调用 this 上的每个函数的目的是什么?那是代替:

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

                this.defaultOptions = {};

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

                return this.each(function() {

                    var $this = $(this);

                });

            }

        });

    })(jQuery);

如果我简单地将this 返回为:

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

            this.defaultOptions = {};

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

            return this;

        }

    });

})(jQuery);

两者的工作方式相同。据我了解this 充当插件中的选定元素。例如,如果我有三个具有 test 类的 div,我这样做了:

$(".test").pluginName(); // returns an array of three div elements in both plugin styles  

据我了解,$(".test") 给出了一个包含三个 dom 元素的数组,并且对于 $(".test").pluginName();,pluginName 被调用了三次,三个返回的值被推送到一个数组中,最后返回。

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

【问题讨论】:

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

标签: javascript jquery jquery-plugins


【解决方案1】:

据我了解 $(".test") 给出了一个包含三个 dom 元素的数组,并且 pluginName 被调用了三次 $(".test").pluginName();并将三个返回值压入一个数组中,最后返回。

这是不正确的。 pluginName() 被调用一次,设置为对应于三个 DOM 元素的 jQuery 对象。所以this.each() 被用来循环遍历 jQuery 对象并为每个对象做任何你需要做的事情。

【讨论】:

    猜你喜欢
    • 2011-04-10
    • 2013-05-26
    • 2010-11-06
    • 2011-04-12
    • 2011-02-10
    • 2021-11-05
    • 1970-01-01
    • 2013-08-09
    相关资源
    最近更新 更多