0

The following function works well. I would like, however, to reuse the same function by passing new parameters. What is the best way of doing that?

function overlay_f (clickable_link, current_link, overlay_content, overlay) {
    var clickable_link = $('.p_wrapper p'),
        overlay = $('#overlay'),
        close_overlay = $('.close_overlay');

    clickable_link.click(function (evt) {
        evt.preventDefault();

        current_link = $(this).attr('class');
        var overlay_content = $('#'+current_link);

        overlay.children().fadeOut(200).promise().done(function () {
            overlay_content.fadeIn();
        });

        overlay.fadeIn();
    });

    overlay.click(function () {
        overlay.fadeOut();
        overlay.children().fadeOut(500);
    });
}    

overlay_f();
4

2 回答 2

1

I think you might be looking for something like this:

function overlay_f(cl, o, co) {
    var clickable_link = $(cl),
    overlay = $(o),
    close_overlay = $(co);

    clickable_link.click(function(evt){
        evt.preventDefault();

        current_link = $(this).attr('class');
        var overlay_content = $('#'+current_link);

        overlay.children().fadeOut(200).promise().done(function () {
            overlay_content.fadeIn();
        });
        overlay.fadeIn();
    });

    overlay.click(function(){
        overlay.fadeOut();
        overlay.children().fadeOut(500);
    });
}   

overlay_f('.p_wrapper p', '#overlay', '.close_overlay');
于 2013-02-14T13:27:41.553 回答
0

Where you're currently just declaring variables with the same names as the parameters (which you never pass arguments to when you call the function), instead check if a value has already been passed, and only initialise to the "default" values if they haven't.

function overlay_f(clickable_link, current_link, overlay_content, overlay) {
    var clickable_link = clickable_link || $('.p_wrapper p'),
        overlay = overlay || $('#overlay'),
        close_overlay = $('.close_overlay');

    clickable_link.click(function (evt) {
        evt.preventDefault();

        var current_link = current_link || $(this).attr('class'),
            overlay_content = overlay_content || $('#' + current_link);

        overlay.children().fadeOut(200).promise().done(function () {
            overlay_content.fadeIn();
        });
        overlay.fadeIn();
    });

    overlay.click(function () {
        overlay.fadeOut();
        overlay.children().fadeOut(500);
    });
}

Then you either call it with no arguments:

overlay_f();

or pass arguments that are what you want to use inside:

overlay_f(arg1, arg2, arg3, arg4);
于 2013-02-14T13:24:34.067 回答