2011-11-03 62 views
1

這很難解釋,所以我在下面包含了一個代碼示例,並提供了一個jsFiddle鏈接來演示此問題。JQuery Animate完全回調稱爲多次

這裏有...我有下面的代碼,我創建了一個JS對象,它具有控制一些基於JQuery(1.6.4)的動畫的方法。如果我同時啓動父級和子級動畫,那麼在父級完全回調中,我會停止子級,父級完整函數會被多次調用。但是,如果我將這些方法從對象中拉出來,那麼我就沒有這個問題。任何想法爲什麼,以及如何在保持對象內包含的所有內容的情況下解決此問題?

http://jsfiddle.net/um3dU/41/

HTML

<div id="parent"> 
    <div id="child"> 
     <div id="scrolling-text"> 
      this is scrolling text to explain the issue I'm running into  
     </div>  
    </div>  
</div> 

CSS

#parent   { position: absolute; left: 0px; top: 0px; width: 960px; height: 100px; background-color: blue; } 
#child   { position: absolute; left: 0px; top: 25px; width: 400px; height: 20px; background-color: red; } 
#scrolling-text { position: absolute; left: 0px; } 

的Javascript

var animation = { 
    startChild : function() { 
     $('#scrolling-text').animate({ 
      left: -400 
     }, 
     10000, 
     function() { alert('child complete function'); });  
    }, 

    stopChild : function() { 
     $('#scrolling-text').stop();   
    }, 

    startParent : function() { 
     $('#parent').animate({ 
      top: 240 
     }, 
     5000, 
     $('#parent').animate({ top: 240 }, 5000, 
      function() { alert('In parent complete function'); this.stopChild(); }.bind(this));  
}  
    } 
}; 

調用對象的方法

animation.startChild(); 
animation.startParent(); 

回答

1

參考您的animation變量調用stopChild()

var animation = { 
    ... 
    startParent: function() { 
     $('#parent').animate({ 
      top: 240 
     }, 
     5000, 
     function() { 
      alert('in parent complete'); 
      animation.stopChild(); 
     }); 
    } 
} 

jsfiddle

+0

父完整的功能仍稱,雖然兩次時。 – Steve

+0

不知道這是爲什麼。然而,在'animation.stopChild()'後面添加'$('#parent')。stop()'。 –

+0

是的,很奇怪。您的修改示例還將調用完整的函數兩次。 – Steve