你不告诉我们在那里这些变量的定义,但我认为他们是全局变量。如果是这样,它们也是全局对象的属性,它在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