【问题标题】:How do I loop a variable in the Javascript function call?如何在 Javascript 函数调用中循环变量?
【发布时间】:2015-06-12 16:46:16
【问题描述】:

对于 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.
    });

}

【问题讨论】:

  • step1 step2 step3 函数是全局的吗?如果是这样,您可以这样做window['step' + i]()
  • 至少,将函数放入一个数组中。但是为什么需要动态调用这样的函数呢?
  • setTimeout("step1()",0);
  • @Legends 将字符串传递给 setTimeout 与调用 eval() 完全相同。

标签: javascript jquery function loops variables


【解决方案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]();
    });
}

【讨论】:

  • @dave 我尝试了这两种方法,但都没有奏效。这是我的代码的结构: $(document).ready(function(){ $("#stepbox1").click(function(){ $("#step1").show(); $("#stepswrapper 部分").not("#step1").hide(); $("#stepbox1").addClass("stepboxactive"); $("#stepboxmain div").not("#stepbox1").removeClass(" stepboxactive"); step1(); }); // ...加上另外三个点击函数。然后: function step1() { // Stuff here } // ...加上另外三个调用的函数按钮 });
【解决方案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]();
    });
}

【讨论】:

  • 当然,这可能有效。但根本需要这样做是一种主要的代码气味。
  • Uuuu 我可以从这里闻到它的味道:D
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多