jQuery plugin callback

2019-05-24 16:59发布

ok, so what i'm trying to do is a plugin that returns a jquery array to be used in a callback function.

let's say that i have this 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);

i want to return those pictures and have acces to them in a callback function. something like this

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

thanks

2条回答
甜甜的少女心
2楼-- · 2019-05-24 17:36
(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)

            });
    }
});

and wheni call the plugin i call it like this:

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

that function after the options represents the callback

查看更多
乱世女痞
3楼-- · 2019-05-24 17:49

I see what you're trying to do. If this is all you're doing, you might consider just adding a live event listener to your plugin.

Try this:

(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);

With that technique, all img's, no matter when they are added to the DOM will be hidden when clicked. That is... after the plugin is called, of course.

查看更多
登录 后发表回答