使用类名来调用同名的变量

Use a class name to call variable of the same name

本文关键字:变量 调用      更新时间:2023-09-26

我有一个div列表,类为"dot",每个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,而不是数字

有没有办法让它读成相关变量?

感谢

您没有向我们展示这些变量是在哪里定义的,但我认为它们是全局变量。如果是这样,它们也是全局对象的属性,在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的函数中声明。如果这些变量已经在更高的作用域中声明,那很酷,但如果它们只在该函数中使用,则应该使用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);
});