为什么当你返回this.each时,你是否必须在jQuery中重新包装它

时间:2013-03-22 16:18:15

标签: javascript jquery

如果已经提出要求我道歉,但我无法在任何地方找到答案。

我已经创建了一个基本的插件shell。

你可以在这里找到代码;

http://codepen.io/anon/pen/dlhjL

我的问题是,为什么我必须在每个函数内部重新包装jQuery?

当我初始化方法时,这已经包含在jQuery中,例如$( 'P')为myplugin();

无论如何都要绕过这个?

2 个答案:

答案 0 :(得分:2)

.each()只给回调一个普通的DOM元素。因此,在.each()回调中,如果要使用jQuery对象,yuo必须从传递它的DOM元素中创建一个。

插件本身以this作为主机jQuery对象开始,这就是为什么你可以执行this.each(),但是.each()this更改为内部的每个连续DOM元素回调,因为它遍历主机jQuery对象中的每个DOM元素。

这里有一些注释:

(function($) {

  $.fn.myPlugin = function() {

      // "this" here is the incoming jQuery object and thus
      //    you can call this.each() to iterate each item in the jQuery object

      return this.each(function() {

          // "this" here is each successive DOM object in the jQuery object
          //    because of how .each() works.
          // If you want to be able to use a jQuery object here, you have
          //    to create one as this code does

          $(this).css('background', 'red');

      });
  };

}(jQuery));

在这种特殊情况下,您实际上并不需要.each()因为.css()将在jQuery对象中的所有DOM元素上为您进行迭代。你可以这样做:

jQuery.fn.myPlugin = function() {
    return this.css('background', 'red');
}

答案 1 :(得分:0)

包装的是所有段落元素,而在.each回调中,同时对所有元素进行操作没有任何意义。

您通常不需要对要迭代的元素进行jQueryify,在这种情况下,您可以编写

return this.css("background-color", "red");