开发者

How can I shorten this code jquery

    $( "#nextFrom1" ).click(function(){
            $( "#widget01" ).fadeOut( "slow", function(){
                    $( "#widget02" ).fadeIn( "slow" );
                });
        });
    $( "#nextFrom2" ).click(function(){
            $( "#widget02" ).fadeOut( "slow", function(){
                    $( "#widget03" ).fadeIn( "slow" );
                });
        });
    $( "#prevFrom3" ).click(functi开发者_运维技巧on(){
            $( "#widget03" ).fadeOut( "slow", function(){
                    $( "#widget02" ).fadeIn( "slow" );
                });
        });
    $( "#prevFrom2" ).click(function(){
            $( "#widget02" ).fadeOut( "slow", function(){
                    $( "#widget01" ).fadeIn( "slow" );
                });
        });

Please guide me in the right direction of shortening this code. Objects maybe?! This is just a small chunk of the ever repeating anonymous functions.


Create a functiont to do the binding for you, passing in your respective ids:

function BindClick(clickId, widgetId1, widgetId2){
    $( clickId ).click(function(){
            $( widgetId1).fadeOut( "slow", function(){
                    $( widgetId2 ).fadeIn( "slow" );
                });
        });
}

And calling:

BindClick("#nextFrom1", "#widget01", "#widget02");
//etc


Maybe something like this:

function makeClickHandler(fadeOut, fadeIn){
    return function(){
        $( "#widget" + fadeOut ).fadeOut( "slow", function(){
            $( "#widget" + fadeIn ).fadeIn( "slow" );
        })
    };
}
$( "#prevFrom2" ).click(makeClickHandler("02", "01") );


Create jquery plugin rather than repeating code

example : http://pranayamr.blogspot.com/2010/11/jquery-plugin-how-and-when-to-use-it.html


Create a jQuery plugin. Here is something to get you started:

(function($) {
    $.fn.directWidget = function(options) {
        var defaults = { 
            /* default options go here */
            hiding: null,
            showing: null,
            speed: 'slow'
        };
        var settings = $.extend({}, defaults, options);

        return this.bind('click.directWidget', function(e) {
            $(settings.hiding).fadeOut(settings.speed, function() {
                $(settings.showing).fadeIn(settings.speed);
            });
        });
    };
})(jQuery);

You can then call like so:

$('#nextFrom1')
    .directWidget({ hiding: '#widget01', showing: '#widget02', speed: 'slow' });
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜