繁体   English   中英

jQuery:因为fadeOut()而避免代码重复

[英]jQuery: avoid code duplication because of fadeOut()

这是我多次面临的问题:

  • 我有一个可能或可能可见的元素
  • 我需要在这个元素中做一些事情
  • 如果元素是可见的,则fadeOut()表示该元素
  • 一旦完成那些东西: fadeIn()那个元素

问题出在这里:我的代码如下所示:

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

我只是想让它干净,所以没有重复same long code (A)

你是如何做到这一点的(通用的方式)?

简单通用解决方案

$('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();
        }
    });

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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