我有一个循环,该循环检查元素的数据属性的内容,然后使用此内容在开关函数中匹配它。我想简化此代码,因为数据属性值可能在下一个将来有所不同,并且每次我都必须在交换机中添加一个情况时。我现在拥有的(这很好):
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"值,使用将值作为var名称,然后在变量内容上工作。
编辑:大多数情况下,我的需求是从案例中进行的一个函数,这是我在上面的代码中使用的方式,目前还可以,但是每2个月我必须添加另一种情况才能使其正常工作。问题是:如何更改上面的代码以使其更加"通用"one_answers"优雅",以较少的代码行?
类似:
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是一个全局var,需要增加数字并将其放在$('#abc')中。例如,我们有:
abc = 0; (global var)
a = abc; (scoped var)
abc++; (abc === 1)
$('#abc').text(abc); (equivalent to $('#abc').text(1);)
因此,我需要在循环中调用" a"值作为全局var的名称,递增它,然后使用'a'作为jQuery选择器,以将其内部增量的全局var的值发短信。我怎样才能做到这一点?
如果我了解您需要做什么,则应尝试使用eval()
eval()函数评估表示为字符串的JavaScript代码。
var a = $('#el').attr('data-x');
for (var i = 0; i <= 2; i++) {
eval(a + "++");
$('#'+a).text(eval(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');}
}