0

如果已经有人问过这个问题,我深表歉意,但我在任何地方都找不到答案。

我创建了一个基本的插件外壳。

你可以在这里找到代码;

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

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

当我初始化该方法时,它已经包含在 jQuery 中,例如 $('p').myPlugin();

有没有办法解决这个问题?

4

2 回答 2

2

.each()只给回调一个普通的 DOM 元素。所以,在.each()回调内部,如果你想使用一个 jQuery 对象,你必须从它传递的 DOM 元素中创建一个。

插件本身以this宿主 jQuery 对象开始,这就是您可以这样做的原因this.each(),但在遍历宿主 jQuery 对象中的每个 DOM 元素时,它会.each()更改为回调内的每个连续 DOM 元素。this

这是一些注释:

(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');
}
于 2013-03-22T16:22:15.937 回答
0

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

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

return this.css("background-color", "red");
于 2013-03-22T16:26:27.240 回答