2011-06-05 44 views
2

嘿,我很好奇這兩個代碼有什麼區別?第一個作品,但第二個沒有?問題將字符串值傳遞給動畫Jquery函數

First >> 
for (i=0; i<$sequencingArray.length; i++){ 
... 
$($sequencingArray[i]).delay(i*100).animate({'margin-left':$masterWidth}); 
... 
} 

Second >> 
$propToAnimate = 'margin-left'; 
for (i=0; i<$sequencingArray.length; i++){ 
... 
$($sequencingArray[i]).delay(i*100).animate({$propToAnimate:$masterWidth}); 
... 
} 

回答

6

這是一個可行的解決方案......

$propToAnimate = {'margin-left': $masterWidth}; 
$($sequencingArray[i]).delay(i*100).animate($propToAnimate); 

「你不能使用一個變量作爲對象文本內的屬性名稱。」 from here

+0

D'oh!你當然是對的! – Pointy 2011-06-05 16:02:54

+0

非常感謝你! – hamahama 2011-06-05 16:55:51

0

當您使用{'margin-left':$masterWidth}{$propToAnimate:$masterWidth}您正在創建一個對象。所以我們需要知道當我們使用Object Initializer{k0:v0, k1:v1})語法創建一個對象時我們正在做什麼。

最重要的是你的情況var a = {prop:20}var a = {'prop':20}都會做同樣的事情 - 創建一個名爲prop的屬性的對象。如果您已在其他地方說過var prop = 'different',則無關緊要,prop僅在{prop:20}中使用時被視爲文字名稱,並且未進行評估。

你可以做的第二個代碼版本的工作是利用對象的a['prop']語法。所以像這樣:

var prop = 'margin-left'; 
var obj = {}; // Create a new object with no propeties 
obj[prop] = masterWidth; // Add a new property to obj (using the value of the variable prop as the name of the new property) 

然後你將有obj['margin-left'] == masterWidth。你可以在動畫功能中使用這個對象... animate(obj);

我希望我一直沒有太困惑!