无法写入非冗余功能

时间:2013-03-06 10:43:57

标签: jquery function

以下代码是我编写的函数的一部分,但不知何故感觉多余。任何人都可以告诉我如何正确接近以下内容:

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

2 个答案:

答案 0 :(得分:3)

制作一个函数:)并在两个地方调用它

更新代码

//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 
  }

}

答案 1 :(得分: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 */
相关问题