2013-03-22 23 views
0

我很抱歉,如果這已被問到,但我找不到答案的任何地方。爲什麼當你返回this.each時,你是否必須在jQuery中重新包裝這個

我創建了一個基本的插件外殼。

你可以在這裏找到代碼;

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

我的問題是,爲什麼我要內jQuery的每個函數內再重新包裝嗎?

當我初始化該方法時,它已經包裝在jQuery中,例如, $( 'P')爲myplugin();

有沒有辦法解決這個問題?

回答

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'); 
} 
+0

大。感謝那 – 2013-03-22 16:51:27

+0

@ User123 - 我添加了一個更簡單的版本。 – jfriend00 2013-03-22 18:20:21

0

什麼是包裹是所有段落元素,而.each回調中它沒有任何意義上在同一時間的所有元素進行操作。

您通常不需要jQueryify正在迭代的元素,在這種情況下,你可以寫

return this.css("background-color", "red"); 
相關問題