使用类名来调用同名的变量
Use a class name to call variable of the same name
我有一个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);
});
相关文章:
- 从带参数的字符串变量调用函数中的函数
- 将方法从控制器注入到未使用右变量调用的指令
- 为什么可以对整数变量调用toString(),而不能对文字数字调用
- 我可以对变量调用“.log”吗?
- 是否可以对超出范围的 setInterval 变量调用 clearInterval 方法
- 对模板中的胡子变量调用方法
- 使用不同的变量调用递归函数
- Jquery中的变量调用
- 将循环变量调用到自动压缩选择中
- 如何在 jquery 中用变量调用变量
- jQuery,从变量调用数组对象的一部分
- 在 AngularJS 中使用绑定变量调用控制器方法
- 如何使用变量调用对象及其方法
- 是否可以对变量调用jquery函数
- Android:从javascript传递变量调用Java中的函数
- 带有变量调用的谷歌地图API实现
- 无法对数字变量调用 toFixed
- 如何将嵌套的全局或本地jquery变量调用到html中
- Javascript:如何通过变量调用函数并传递参数
- 对字符串变量调用toUppercase()