fadeIn / fadeOut based on a boolean

后端 未结 2 1422
眼角桃花
眼角桃花 2021-02-19 23:02

I was wondering if I really have to write:

if (status) {
    $(\'#status-image-\' + id).fadeIn();
} else {
    $(\'#status-image-\' + id).fadeOut();
}

相关标签:
2条回答
  • 2021-02-19 23:22

    No, there is not, but you can make one like that:

    jQuery.fn.fadeInOrOut = function(status){
        return status ? this.fadeIn() : this.fadeOut();
    }
    

    and then call it like that (see this jsfiddle for a proof):

    $('#status-image-' + id).fadeInOrOut(status);
    

    Is it what you wanted?

    0 讨论(0)
  • 2021-02-19 23:30

    The shortest way I know of to write this, but one I find personally abhorrent, is this:

    $('#status-image-' + id)[status ? 'fadeIn' : 'fadeOut']();
    

    You can of course just add the proposed function straight to jQuery:

    (function($) {
        $.fn.fade = function() {
            var args = Array.prototype.slice.call(arguments);  
            var status = args.shift();
            var func = status ? 'fadeIn' : 'fadeOut';
            return $.fn[func].apply(this, args);
        };
    })(jQuery);
    

    This is untested - I just knocked it up on the spot.

    The first argument supplied will be your status parameter - the remaining arguments will be passed through to .fadeIn() or .fadeOut().

    0 讨论(0)
提交回复
热议问题