2012-01-09 39 views
1

下面是一个循环,它创建了六个不同颜色的框。当点击一个框时,变量“color”变成框的颜色。代码存在一个明显的问题,那就是关闭(所有的框都获得数组中的最后一个类,boxColors [i]不可能在事件内部使用(undefined)。闭环问题(事件)

如何解决这个问题一个优雅的方式?在此先感谢。

var boxColors = ['red', 'green', 'blue', 'yellow', 'white', 'black']; 

for (var i = 0; i < boxColors.length; i++){ 
    $('<div/>', { 
     'class': boxColors[i] 
    }).appendTo(toolboxSection1).click(function(){ 
     color = boxColors[i]; 
    });  
} 
+0

*” ......所有的箱子得到的最后一堂课在阵列中......“*你确定吗?每个元素都应该从数组中获得唯一的类,所以唯一的问题应该是事件处理程序(可以轻松访问元素的'className'属性)。 – 2012-01-10 00:08:27

回答

4

JavaScript closure inside loops – simple practical example中描述了此问题的一个示例以及如何在一般情况下解决该问题。

然而,jQuery的允许你传递附加数据的事件处理程序(见documentation),这是另一种方式来解决这个问题:

for (var i = 0; i < boxColors.length; i++){ 
    $('<div/>', { 
     'class': boxColors[i] 
    }) 
    .appendTo(toolboxSection1) 
    .click({color: boxColors[i]}, function(event){ 
     // event.data.color 
    });  
} 
1

的问题是你的for循环捕捉他们的boxColors.length计数单变量i来代替。解决这个问题的最简单的方法是创建一个新的函数,该函数索引作为参数并因此为每次迭代创建新的i

var action = function(i) { 
    $('<div/>', { 
     'class': boxColors[i] 
    }).appendTo(toolboxSection1).click(function(){ 
     color = boxColors[i]; 
    }); 
}; 

for (var index = 0; index < boxColors.length; index++) { 
    action(index); 
}