2011-03-11 63 views
0

我對jQuery比較新,我想知道如果我做的下面的 函數是以最優雅的方式生成的嗎? 任何信息非常感謝!謝謝優雅的jQuery功能

$(function(){ 
     $('#enter').click(function() { 
      $('#enter').fadeOut(80, function() { 
      $('#enter').hide(function() { 
      $('#overlay').fadeIn(1500, function() { 
      $("#loading").show().delay(500); 
      $("#loading").hide(function(){ $("#s5").show(); }); 
      return false; 

     }); 
    }); 
    }); 
     $('#slideTop').animate({ 
      marginTop: '-=230' 
     }, 500, function() { 
    }); 
     $('#slideBottom').animate({ 
      marginBottom: '-=333', 
     }, 500, function() { 
    }); 

     }); 
    }); 

我應該有它的開始是這樣的:

$(function(){ 
var cintro = function(){ 
    $('#box').click(function(){ 
     $(this).slideUp(
      {duration:1000}//2000,easing:"easeOutBounce" 
     ); 
    setTimeout(function(){ 
     ('#box').slideUp(
      {duration:1000}//2000 
     );}, 6000); 
    //$('#box').css({'display': 'block'}).click(function(){$(this).css('display', 'none'); 
}); 
    $('#slidenav').slideDown({duration:2000,easing:"easeOutBounce"}); 
    $('#slider1').data('AnythingSlider').startStop(true); 
} 
$('#enter').click(cintro); 
}); 
+1

你的問題有點主觀,定義_elegant_,你是指最小/最簡單/最少量的代碼方式來做你想做的事情? – gideon 2011-03-11 04:02:59

+0

就像在末尾使用一個變量來處理點擊事件一樣 – iamwhitebox 2011-03-11 04:08:10

回答

0

我不是一個jQuery的專家,但也有幾件事情我會改變這一點。

如果我從DOM一遍又一遍相同的對象進行交互我通常在恆定的初始化它,而不是選擇它每次:

var $ENTER_BUTTON = null; 
...[other elements]... 

$(document).ready(function(){ 
    $ENTER_BUTTON = $('#enter'); 
    ... [etc] ... 
}); 

你也不需要遵循fadeOut與 AFAIK。這是多餘的。

如果其他動畫可能會適當地干擾轉換,請使用stop()

最後,如果有這些轉變可以從頁面的其他部分,被調用或者,如果你想使你的代碼多一點可讀性我會定義一個函數和引用該函數:

function enterAnimation(){ 
    $ENTER_BUTTON.fadeOut(80,function(){ 
    ... etc 
}  

$(document).ready(function(){ 
    $ENTER_BUTTON = $('#enter'); 
    ... [etc] ... 
    $ENTER_BUTTON.click(enterAnimation); 
});  
1
$(function(){ 
    // cache some selectors that won't ever change 
    var enter = $('#enter'), 
     overlay = $('#overlay'), 
     loading = $('#loading'), 
     s5 = $('#s5'), 
     slideTop = $('#slideTop'), 
     slideBottom = $('#slideBottom'); 

    enter.click(function() { 
    enter.fadeOut(80, function() { 
     // i don't think you really need this .hide() but you might... 
     enter.hide(); 
     overlay.fadeIn(1500, function() { 
     loading.show().delay(500).hide('slow', function() { 
      $("#s5").show(); 
     }) 
     }); 
    }); 
    return false; 
    }); 

    slideTop.animate({ 
    marginTop: '-=230' 
    }, 500); 
    slideBottom.animate({ 
    marginBottom: '-=333', 
    }, 500); 
});