开发者

jQuery plugin callback

开发者 https://www.devze.com 2022-12-08 17:49 出处:网络
ok, so what i\'m trying to do is a plugin that returns a jquery array to be used in a callback function.开发者_高级运维

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


(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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消