简体   繁体   中英

jQuery: avoid code duplication because of fadeOut()

Here's the problem I've faced many times:

  • I have an element that may or may not be visible
  • I need to do some stuff into that element
  • if the element is a visible, fadeOut() that element
  • once that stuff is done: fadeIn() that element

The problem is here: my code looks like this:

function showOnlyElement(myEl)
{
    $('body')
        .children('div:not(.'+myEl+')')
        .fadeOut()
        .promise().done(function() {
            var el=b.children('div.'+myEl);
            if (el.is(':visible')) {
                /* I have to hide it before modifying it */
                el.fadeOut(function() {
                    /* long code (A) modifying the innerHTML of el */
                    el.fadeIn();
                });
            } else {
                /* AGAIN same long code (A) modifying the innerHTML of el */
                el.fadeIn();
            }
        });
}

I just want make it clean so there's not repetition of the same long code (A)

How do you do this (generic way of doing this)?

Simple generic solution :

$('body')
    .children('div:not(.'+myEl+')')
    .fadeOut()
    .promise().done(function() {
        var el=b.children('div.'+myEl);
        function longCode(){
            /* long code (A) modifying the innerHTML of el */
            el.fadeIn();
        }
        if (el.is(':visible')) {
            el.fadeOut(longCode);
        } else {
            longCode();
        }
    });

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