我有一个16x16的按钮网格,并想要为每个按钮添加事件监听器,当其被点击时返回其唯一的网格位置编号(范围在0-255之间);
目前我的代码如下:
public static const GRID_SIZE:Number = 16;
private var i:int;
private var j:int;
// Constructor
public function Grid()
{
for (i = 0; i < GRID_SIZE; i++)
{
for (j = 0; j < GRID_SIZE; j++)
{
// Creates new instance of GridButton, a custom class that extends SimpleButton
var button:GridButton = new GridButton();
// Arranges buttons into a grid
button.x = (i + 1) * button.width;
button.y = (j + 1) * button.height;
// Create unique value for grid position
var position:Number = i * GRID_SIZE + j;
// Add listener to button, with position as extra param
button.addEventListener(MouseEvent.CLICK, function(e:MouseEvent) : void { buttonClick(e, position) } );
// Adds button to Sprite
addChild(button);
}
}
}
}
很遗憾,每次每个按钮调用监听器函数时,它使用i和j的最后两个值,这种情况下每个按钮返回255。
有什么建议吗?