我有一个带有“点”类的 div 列表,以及每个城镇名称的不同类(例如伦敦、格拉斯哥等)
我正在尝试将第二个类名用作函数中的变量。如果我将第二个类名回显到函数中,它会将其读取为一个字符串,而不是代表数字的变量...
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 而不是数字
有什么方法可以让它作为相关变量读取吗?
谢谢
最佳答案
你没有告诉我们这些变量是在哪里定义的,但我假设它们是全局变量。如果是这样,它们也是全局对象的属性,在网络浏览器中是 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
声明。如果这些变量已经在更高的范围内声明了,那很好,但是如果它们只在那个函数中使用,你应该在那个函数中使用 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);
});
关于javascript - 使用类名调用同名变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25642268/