js如何通过变量名调用函数

比如:
function SetDataStyle (curNumber,totalNumber,style) {
var func = 'SetStyle'+style;
//? func(curNumber,totalNumber);

}
function SetStyle0(curNumber,totalNumber){
}
function SetStyle1(curNumber,totalNumber){
}我希望当用户传入style=0时调用SetStyle0,依次类推,怎么处理呢?

需要准备的材料分别是:电脑、html编辑器、浏览器。

1、首先,打开html编辑器,新建html文件,例如:index.html,填充基础代码。

2、在index.html的<script>标签中,输入js代码:eval(func + '()');。

3、浏览器运行index.html页面,此时会看到传入不同的style确实能调用到不同的SetStyle函数来打印。

温馨提示:答案为网友推荐,仅供参考
第1个回答  推荐于2017-11-25
function SetDataStyle(curNumber, totalNumber, style) {
var func = 'SetStyle' + style;
// 所以你可以用window[方法名](参数)的方式调用;
window[func](curNumber, totalNumber);
}
// 这个方法会加到window对象下面
function SetStyle0(curNumber, totalNumber) {
alert('SetStyle0');
}
// 这个方法会加到window对象下面
function SetStyle1(curNumber, totalNumber) {
alert('SetStyle1');
}
SetDataStyle(1, 1, 0);

本回答被提问者采纳
第2个回答  2013-04-26
<script>
function a(number){
eval("a"+number+"()");
}
function a0(){
alert("OK!");
}
a(0);
</script>

你好,可以用eval().请测试~

第3个回答  2013-04-26
将变量名绑定上函数就可以了
fucntion a() {alert(1);}
var b = a();
第4个回答  2013-04-26
function SetDataStyle (curNumber,totalNumber,style) {
var func = 'SetStyle'+style;
var f = eval(func);
f(curNumber,totalNumber);

}本回答被网友采纳

相关了解……

你可能感兴趣的内容

本站内容来自于网友发表,不代表本站立场,仅表示其个人看法,不对其真实性、正确性、有效性作任何的担保
相关事宜请发邮件给我们
© 非常风气网