2012-04-19 124 views
2

我的腳本有什麼問題?當我執行它時,警報(第2行)給了我「100,200,300undefinedundefined」,所以當我希望它是h1,h2和h3(用逗號)時,似乎100,200,300被解釋爲h1。Javascript函數變量問題

function myanimation(h1,h2,h3) { 

     alert(h1 + h2 + h3); 
     $("#h1").animate({"left": h1}); 
     $("#h2").animate({"left": h2}); 
    } 

    var moves = new Array() 
    moves[1] = [100,200,300]; 
    moves[2] = [300,200,100]; 
    moves[3] = [-500,-300,0]; 

    var i = 1; 

    function animatenow(){ 
     myanimation(moves[i]); 
     i++; 
    } 

$('#launch').click(function() { 
     setInterval(animatenow, 5000); 
    }); 

回答

2

亞當,你是傳遞一個數組對象爲H1,而不是獨立的變量

你可能想改變

myanimation(moves[i]); 

到:

myanimation(moves[i][0],moves[i][1],moves[i][2]); 
+0

另一個問題:當我在我的函數中使用i ++時,它不起作用;它總是發送移動[1],所以我如何使i ++範圍成爲全局而不是本地? – 2012-04-19 18:26:59

+0

@AdamStrudwick它不會那樣對我。有沒有其他的代碼可能會重置我? – 2012-04-19 20:00:41

6

你傳遞一個數組myanimation,這相當於你h1參數。你沒有通過h2h3,所以這些都是未定義的。

2

你傳遞一個數組到myanimation它期望三個參數。

myanimation(moves[i]);其中moves[1] = [100,200,300]

所以h1myanimation[100,200,300]

改變它期望數組:根據您的代碼

function myanimation(moves) { 
    $("#h1").animate({"left": moves[1]}); // moves[1] is 100 
    $("#h2").animate({"left": moves[2]}); // 200 
} 
0

,應在下述代碼這樣的嗎?

function animatenow(){ 
    myanimation(moves[i][0], moves[i][1], moves[i][2]); 
    i++; 
} 
+0

另一個問題:當我在我的函數中使用i ++時,它不起作用;它總是發送移動[1],所以我如何使i ++範圍成爲全局而不是本地? – 2012-04-19 18:33:07