我有一个循环,它检查元素的data-attribute的内容,然后使用这个内容在switch函数中匹配它。我想简化这段代码,因为数据属性值可能在未来将有所不同,并且每次我都必须向交换机添加一个案例。 我有什么现在(这工作正常):如何更改从循环中的数据属性获取变量名称的变量内容?
var a = $('#el').attr('data-x'); // String
for (var i = 0; i <= 2; i++) {
switch (a) {
case "abc":
abc++; // variable initially set to 0
$('#abc').text(abc); // Overwrite the content with the new value
break;
case "dfg":
dfg++;
$('#dfg').text(dfg);
break;
[ ...Many cases like the ones listed here ]
}
if (i === 0) { a = $('#el').attr('data-x1')}
else if (i === 1) { a = $('#el').attr('data-x2');}
else if (i === 2) { a = $('#el').attr('data-x3');}
}
我想实现的是采取的“a”值,使用作为一个变量名称的值,然后对变量的内容合作。
编辑:大多数情况下,我的需要是一个函数,不依赖于案例,我在上面的代码中使用的方式现在可以,但是每隔2个月我必须添加另一个案例以使其工作。问题是:如何更改我的代码以使其在更少的代码行中更“普遍”和“优雅”?
喜欢的东西:
var a = $('#el').attr('data-x');
for (var i = 0; i <= 2; i++) {
a++; // 'a' must be the name of the var, the name of the variable it's the same as $('#el').attr('data-x').
// So, 'a' var will change every time the function it's executed as in the switch version of the first block of code above (abc++ or dfg++).
$('#'+a).text(a);
if (i === 0) { a = $('#el').attr('data-x1')}
else if (i === 1) { a = $('#el').attr('data-x2');}
else if (i === 2) { a = $('#el').attr('data-x3');}
}
这里长眠着我的问题:“A”将是一个字符串(“ABC”为例),ABC是需要递增,并放置在$数的全局变量( '#abc')。下面我们就针对例如:
abc = 0; (global var)
a = abc; (scoped var)
abc++; (abc === 1)
$('#abc').text(abc); (equivalent to $('#abc').text(1);)
所以我需要在循环中调用的“a”值作为全局变量的名称,增加它,然后用“A”作为一个jQuery选择为文本它内部递增的全局变量的值。 我该怎么做?
你可以告诉你的是从该代码得到什么错误,什么是做++的目的;? –
代码的第一块工作正常,我不知道如何更改由另一个变量的内容命名的变量 –
你能告诉做一个++的目的是什么;?我认为你不需要增加'a'来匹配第一块代码的功能。 –