2009-10-09 72 views
2

好吧,所以我想要做的是一個插件,返回一個jQuery數組用於回調函數。jQuery插件回調

讓我們說,我有這個code``

(function($){ 
$.fn.extend({ 
    //plugin name 
    myPlugin : function(needed){ 

     var defaults = { 
      path : 'action.php', 
      source : '' 
     } 
     var needed = $.extend(defaults,needed); 

     //return 
     return this.each(function(){ 
      //it loads some pictures 
      $('#selector').load(needed.path,{'src':nedeed.source}) 

     }); 
    } 
}); 

})(jQuery的);

我想返回這些圖片,並在回調函數中訪問它們。這個東西

$('#another_selector').click(function(){ 
     $(this).myPlugin({'source':'path/...etc'},function(){ 
       $('img').click(function(){ 
         $(this).remove(); 
}); 
}); 
    }); 

感謝像

回答

1
(function($){ 
    $.fn.extend({ 
    //plugin name 
    myPlugin : function(needed,callback){ 

      var defaults = { 
        path : 'action.php', 
        source : '' 
      } 
      var needed = $.extend(defaults,needed); 

      //return 
      return this.each(function(){ 
        //it loads some pictures 
        $('#selector').load(needed.path,{'src':nedeed.source},callback) 

      }); 
    } 
}); 

和wheni調用插件我這樣稱呼它:

$('#another_selector').click(function(){ 
    $(this).myPlugin({'source':'path/...etc'},function(){ 
      $('img').click(function(){ 
        $(this).remove(); 
}); 
}); 
    }); 

選項後函數表示回調

0

我看到你想要做什麼。如果你只是這麼做的,你可能會考慮在你的插件中添加一個live事件監聽器。

試試這個:

(function($){ 
    $.fn.extend({ 
     //plugin name 
     myPlugin : function(needed){ 
       // New 
       $('img').live('click',function() { 
        $(this).remove(); 
       }); 
       // end new 
       var defaults = { 
         path : 'action.php', 
         source : '' 
       } 
       var needed = $.extend(defaults,needed); 

       //return 
       return this.each(function(){ 
         //it loads some pictures 
         $('#selector').load(needed.path,{'src':nedeed.source}) 

       }); 
     } 
    }); 
})(jQuery); 

有了這種技術,所有的IMG的,無論什麼時候,他們被添加到DOM點擊時會被隱藏。那是在插件被調用之後,當然。

+0

好了,我的插件是複雜多了,但我只是簡化它更全面。我會嘗試你所說的話,如果你的建議適合我,我會告訴你。感謝 – kmunky 2009-10-09 18:59:58

+0

在mouseOver上我想要懸浮動作(出現/消失編輯欄)的每個圖像。在這種情況下,我應該怎麼做?像這樣? $( 'IMG')。住( '的mouseenter',函數(){$ (這).hover( 函數(){彈出編輯欄}, 功能(){編輯欄被隱藏} ); }); – kmunky 2009-10-09 19:05:38