2014-09-03 23 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