简体   繁体   中英

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(function(){
            $( "#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' });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM