2017-04-06 61 views
0

我尝试使用jquery(jquery-2.1.1)和构造函数来构建html。但是当我在for循环中尝试这种方法时,循环无法停止。谁能告诉我为什么会发生?为什么这个循环无法停止?

下面是代码。非常感谢。

function tag() { 
    this.addClass = function(...theArgs) { 
     for (index in theArgs) { 
      this.$html.addClass(theArgs[index]); 
     }  
    } 

    this.setAttr = function(attr, value) { 
     this.$html.attr(attr, value); 
    } 

    this.append = function(...theArgs) { 
     for (index in theArgs) { 
      this.$html.append(theArgs[index]); 
     } 
    } 

    this.find = function(value) { 
     return this.$html.find(value); 
    } 

    this.empty = function() { 
     this.$html.empty(); 
    } 

    this.remove = function(value) { 
     this.find(value).remove(); 
    } 

    this.clone = function() { 
     return jQuery.extend(true, {}, this); 
    } 

    this.show = function() { 
     return this.$html[0]; 
    } 
} 

function label(text) { 
    tag.call(this); 

    this.$html = $("<label></label>"); 
    this.append(text); 
} 


for(var index = 0; index < 2; index++) { 
     var fieldLabel = new label(1); 
     console.log(index); 
} 
+0

在'.append()'中有一个undeclard'index',它们有冲突:'for(index中的Args){'。一定要声明你的变量:'for(varArgs在Args中){' – 2017-04-06 14:21:40

+0

...同样在'addClass()'中。使用类似ESLint的linter来查找这些常见错误。它会为你节省很多很多时间。 – 2017-04-06 14:22:48

+2

...并且在数组中使用'for-in'在JS中并不是一个好主意。既然你使用'...'语法,你必须使用ES6的东西,所以我建议使用'for-for'循环。 – 2017-04-06 14:25:27

回答

0

这里的问题是,你使用index(不var)作为运行变量在您tag功能全部循环。该index变量在末尾for-loop的外部范围内仍然有效(应该在条件为>=2时停止)。

在循环开始时,index0。下一个循环应该是1。但是当进入内部方法append时,由于循环for-in(传入的参数仅为1,因此扩展表示法使数组长度为1,并且for-in停止,并且index设置为0),它重置为0。所以在第二个循环结束时,它仍然是0。这意味着它永远不会变得更大的值1(仅在for-loop开始时增加)。条件< 2将始终得到满足,for-loop将永远运行。

您可以在运行变量for-in中使用其他名称。或者只是声明另一个局部范围的使用var,这样index

this.append = function(...theArgs) { 
    for (var index in theArgs) { 
     this.$html.append(theArgs[index]); 
    } 
} 

或者更好的使用for-of有人建议。

+0

我收到了你,谢谢 –

+0

@CharlesZhou如果有帮助,请花时间接受答案。否则,你应该删除你的问题,因为看起来只是一个简单的错误,并没有被别人利用。 –

相关问题