簡體   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