2013-03-06 80 views
0

下面的代碼是我寫的功能的一部分,但不知何故它感覺多餘。誰能告訴我如何正確處理以下情況:無法寫入非冗餘功能

openProject: function() { 

    if($(a).height() == $(b).height()){ 

     $(myID) 
     .css({ opacity: 0 }) 
     .show() 
     .stop(true, true) 
     .animate({ opacity: 1}, 750); 

    }else{ /* end $(a).height() == $(b).height() */ 

     $(a).stop(true, true).animate({ height : $(b).height() }, 750, function(){ 

      $(myID) 
      .css({ opacity: 0 }) 
      .show() 
      .stop(true, true) 
      .animate({ opacity: 1}, 750); 

     }); 

    } /* end if:else */ 

} 

唯一不同的兩部分之間是用是否$(a)是動畫。

任何幫助將不勝感激!

感謝, Knal

+1

將'$(myID)...;'部分提取到if/else之上聲明的函數中。 – DCoder 2013-03-06 10:46:04

+0

感謝您的回覆。我稍微更新了代碼,以提供更好的印象。 – knalpiap 2013-03-06 10:51:07

+0

更新了我的答案..檢查出來...... – bipen 2013-03-06 11:10:47

回答

3

使得函數:),並調用它在兩個palces

更新的代碼

//seperate function 
function myIdAnimate(){ 
    $(myID) 
    .css({ opacity: 0 }) 
    .show() 
    .stop(true, true) 
    .animate({ opacity: 1}, 750); 
} 

//your code 
openProject: function() { 

    if($(a).height() == $(b).height()){ 
    myIdAnimate(); //just call the function here 
    }else{ /* end $(a).height() == $(b).height() */ 
    $(a).stop(true, true).animate({ height : $(b).height() }, 750, myIdAnimate()); //and here 
    } 

} 
+0

感謝您的回覆。當代碼已經在另一個函數中時,你還會建議嗎? (見更新的代碼) 這樣我會得到很多單獨的功能... – knalpiap 2013-03-06 10:50:27

+0

是的...分離功能的代碼是更好的可讀性... :) :) ..自己檢查更新..;) .... – bipen 2013-03-06 10:56:31

+0

謝謝,我明白了! – knalpiap 2013-03-06 11:18:27

2

你只需要編寫一個小功能:

var resetIdSelector = function(idSelector){ 
    idSelector 
    .css({ opacity: 0 }) 
    .show() 
    .stop(true, true) 
    .animate({ opacity: 1}, 750); 
} 

並將其命名爲:

if($(a).height() == $(b).height()){ 
    resetIdSelector($(myID)); 
}else{ /* end $(a).height() == $(b).height() */ 
    $(a).stop(true, true).animate({ height : $(b).height() }, 750, function(){ 
     resetIdSelector($(myID)); 
    }); 

} /* end if:else */ 
+0

也是一個正確的答案,謝謝! 太糟糕了,我只能指定一個答案作爲正確的答案... – knalpiap 2013-03-06 11:19:03