如何缩短此代码jquery

时间:2011-04-20 19:03:17

标签: javascript 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" );
                });
        });

请指导我缩短此代码的正确方向。对象可能?!这只是重复匿名函数中的一小部分。

4 个答案:

答案 0 :(得分:4)

创建一个函数来为你做绑定,传入你各自的id:

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

并致电:

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

答案 1 :(得分:3)

也许是这样的:

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

答案 2 :(得分:2)

答案 3 :(得分:1)

创建一个jQuery插件。这是让你入门的东西:

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

然后您可以这样打电话:

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