如何在jquery插件中使用“return this”?

时间:2013-10-02 15:06:39

标签: jquery

当我们使用return this?时,从代码1和代码2下面的哪一个是真的?

code1:

   $.fn.greenify = function() {
      $.each(function() {
        this.css( "color", "green" );
        return this;
      };
   };

code2:

      $.fn.greenify = function() {
      $.each(function() {
        this.css( "color", "green" );
      };
      return this;
   };

2 个答案:

答案 0 :(得分:1)

那将是:

$.fn.greenify = function() {
  return this.each(function() {
      $(this).css( "color", "green" );
  });
};

返回传递的集合以确保插件可以链接 另一方面,如果这是你的插件,那么就不需要each

$.fn.greenify = function() {
     return this.css( "color", "green" );
};

答案 1 :(得分:0)

您可以返回.each()的结果:

$.fn.greenify = function() {
   return this.each(function() {
     this.css( "color", "green" );
   };
};

请参阅plugin tutorial page上标题为“使用each()方法”的部分。

相关问题