2011-05-07 149 views
3

我知道這已被回答,但似乎沒有一個問題與我的觀點完全相關。我的代碼如下。我需要將變量$dynamicPanel轉入第二個函數,或將this轉入第二個函數。無論哪種方式都是可以接受的。將HTML元素傳遞給Javascript函數

雖然我們在這樣做,有沒有什麼辦法可以等待幾秒鐘來執行FirstAnimation函數,而無需再次使用animate()方法。

$(document).ready(function FirstAnimation() { 
    var $dynamicPanel = $(".dynamicPanel"); 
    $('.dynamicPanel').animate({ 
     opacity: 0, 
     left: '100' 
    }, 5000, function() { 
     alert('first animation complete'); 
     SecondAnimation(this); 
    }); 
}); 

function SecondAnimation(this) { 
    $(this).animate({ 
     opacity: 1 
    }, 100, function() { 
     alert('second animation complete'); 
     FirstAnimation(); 
    }); 
}; 

回答

2

this是保留字,不能用作參數名稱。你應該這樣做:

$(document).ready(function(){ 
    FirstAnimation(); 
}); 

function FirstAnimation() { 
    //this function doesn't change, use your code 
}; 

function SecondAnimation(elem) {   
    $(elem).animate({ 
     opacity: 1 
    }, 100, function() { 
     alert('second animation complete'); 
     setTimeout(function(){ //Delay FirstAnimation 7 seconds 
      FirstAnimation(); 
     }, 7000); 
    });  
}; 

希望這會有所幫助。歡呼聲

0

那麼如何將SecondAnimation(this);更改爲SecondAnimation($dynamicPanel);?它看起來會做你想做的。

0

這個等待可以jQuery.delay()

$(document).ready(function FirstAnimation() { 
    var $dynamicPanel = $(".dynamicPanel"); 
    $dynamicPanel.animate({ 
     opacity: 0, 
     left: '100' 
    }, 5000, function() { 
     alert('first animation complete'); 
     SecondAnimation($dynamicPanel); // <--pass the proper variable ;) 
    }); 
}); 

function SecondAnimation(this) { 
    $(this).delay(5000).animate({ //<<-- wait five seconds 
     opacity: 1 
    }, 100, function() { 
     alert('second animation complete'); 
     FirstAnimation(); 
    }); 
}; 

做但你可以調用功能全遞歸和數組通過動畫設置爲PARAMATERS。所以你重用的功能和只改變行爲

// store animationsettings in an array; 
var animationSettings = [{opacity: 0, left: '100'},{ opacity: 1 }]; 
// initialize the startup index 
var x = 1; 
// cache selector 
var $dynamicPanel = $(".dynamicPanel"); 
// single function 
(function animate(){ 
    x = x == 1 ? 0 : 1;//<--- toggle the index 
    $dynamicPanel.delay(x * 5000).animate(animationSettings[x], 
     1000, 
     function() { 
      animate(); // recursive call this function. 
     }); 
}()); 

fiddle here

0

使用SecondAnimation.apply(this)