如何在Javascript函数调用中循环变量?

时间:2015-04-07 22:37:24

标签: javascript jquery function loops variables

我在jQuery中有一系列类似的点击事件的循环。一切正常,除了下面的最后一行和评论。如何让每个循环迭代分别调用这些函数:step1(),step2(),step3()等?

for (i = 0; i < 7; i++) {

    $("#stepbox" + i).click(function(){
    $("#step" + i).show();                     
    $("#stepswrapper section").not("#step" + i).hide();
    $("#stepbox" + i).addClass("stepboxactive");
    $("#stepboxmain div").not("#stepbox" + i).removeClass("stepboxactive");
    step + i(); // I'm stuck here. This doesn't work to create the function calls step1(), step2(), etc.
    });

}

2 个答案:

答案 0 :(得分:2)

假设您的函数是在全局上下文中定义的:

for (i = 0; i < 7; i++) {

    $("#stepbox" + i).click(function(){
        $("#step" + i).show();                     
        $("#stepswrapper section").not("#step" + i).hide();
        $("#stepbox" + i).addClass("stepboxactive");
        $("#stepboxmain div").not("#stepbox" + i).removeClass("stepboxactive");
        window["step" + i]();
    });
}

答案 1 :(得分:1)

创建一个步骤函数数组。

var step = [
  function () { /* step 0 */ },
  function () { /* step 1 */ },
  function () { /* step 2 */ }
  // ...
];
for (i = 0; i < 7; i++) {
    $("#stepbox" + i).click(function(){
        $("#step" + i).show();                     
        $("#stepswrapper section").not("#step" + i).hide();
        $("#stepbox" + i).addClass("stepboxactive");
        $("#stepboxmain div").not("#stepbox" + i).removeClass("stepboxactive");
        step[i]();
    });
}