javascript - 使用类名调用同名变量

标签 javascript jquery html css

我有一个带有“点”类的 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/

相关文章:

javascript - 最佳数据库连接数(node-mysql)

javascript - 为什么 isPrototypeOf 返回 false,但我可以沿着原型(prototype)链向上?

javascript - 在 JavaScript(ES6) 的构造函数链中调用被子函数覆盖的父函数

javascript - 打印样式表不影响使用 javascript

javascript - 使用 js mouseover 和 mouseout 更改背景颜色

html - 如何在无响应的移动网站上设置视口(viewport)?

javascript - PHP/Laravel : POSTed JSON Object Array not setting keys with empty values

javascript - 如果超过 x 秒没有点击某个其他 div,则显示 div

javascript - 在 div 悬停时显示 chop 的文本

css - 能否在网页上的单个图形图像周围和顶部放置多个事件元素?