2014-09-03 59 views
1

我有一個div類的列表,其中包含類「dot」以及每個鎮上名稱不同的類(例如,倫敦,格拉斯哥等)使用類名稱調用同名變量

我想使用第二個類名作爲函數中的變量。如果我同意第二類名進入它讀取它只是相對於它代表了許多變量的字符串函數...

var resize = function() { 
    $('.dot').each(function() { 
     uniName = $(this).attr('class').split(' ')[1]; 
     uniNameMargin = uniName/2 - uniName; 
     $('.' + uniName).animate({ 
      width: uniName, 
      height: uniName, 
      marginLeft: uniNameMargin, 
      marginBottom: uniNameMargin 
     }, 300); 
    }); 

目前這個公式試圖使用的話爲數字並返回很多NaN而不是數字

有什麼辦法讓它把它看作是相關的變量嗎?

感謝

+0

嘗試在'String()'中包裝變量? – Newtt 2014-09-03 10:45:08

+1

你應該使用'parseInt(val,10)' – 2014-09-03 10:45:15

+0

只需加'+轉換爲整數,如:'uniNameMargin = + uniName/2 - uniName;' – 2014-09-03 10:47:43

回答

2

你不告訴我們在那裏這些變量的定義,但我認爲他們是全局變量。如果是這樣,它們也是全局對象的屬性,它在Web瀏覽器中是window屬性。

如果你有一個對象的屬性名作爲一個字符串,您可以用方括號訪問屬性:

var my_object; 
my_object.london = 1; 

var property_name = "london"; 
console.log(my_object[property_name]); // Will log 1 to the console 

所以,你可以訪問你的變量這樣的值(正如我所說,假設他們是全局變量):

uniName = $(this).attr('class').split(' ')[1]; // After this line, I’m assuming uniName has a value like "london" 
    var uniNumber = window[uniName]; 
    uniNameMargin = uniNumber/2 - uniNumber; // Here, we use [] notation to access the "london" property of the window object. If you have a global variable called "london" with a numerical value, this should now work. 

我也注意到,在您$('.dot').each函數中的變量不使用函數內聲明。如果這些變量已經在較高範圍內聲明,那麼很酷,但如果它們只用於該函數中,則應該使用關鍵字var在該函數中聲明它們,以便不污染父級或全局範圍你不需要的變量:

$('.dot').each(function() { 
    var uniName = $(this).attr('class').split(' ')[1]; 

    var uniNumber = window[uniName]; 

    var uniNameMargin = uniNumber/2 - uniNumber; 

    $('.' + uniName).animate({ 
     width: uniName, 
     height: uniName, 
     marginLeft: uniNameMargin, 
     marginBottom: uniNameMargin 
    }, 300); 
}); 
+2

'window [uniName]/2 - window [uniName];' – noamtcohen 2014-09-03 10:55:46

+0

@noam:ooh,是的。謝謝。 – 2014-09-03 10:57:51

+1

太棒了。很好,謝謝你的解釋! – bboybeatle 2014-09-03 11:10:30