你不告訴我們在那裏這些變量的定義,但我認爲他們是全局變量。如果是這樣,它們也是全局對象的屬性,它在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);
});
嘗試在'String()'中包裝變量? – Newtt 2014-09-03 10:45:08
你應該使用'parseInt(val,10)' – 2014-09-03 10:45:15
只需加'+轉換爲整數,如:'uniNameMargin = + uniName/2 - uniName;' – 2014-09-03 10:47:43