0

我正在尝试创建一个显示您按下的按钮名称的系统。按钮名称被放入一个数组中,但是它只识别最后一个输入到数组中的项目。帮助将不胜感激。

var items:Array = [a, b, c]; //The name of each button

for each(var index in items) 
{
    index.addEventListener(MouseEvent.CLICK, mouseClickHandler);
}

function mouseClickHandler(event:MouseEvent):void
{
    trace(index.name); //Should display the name of any of the buttons clicked.

}
4

2 回答 2

3

您应该跟踪currentTarget名称:

var items:Array = [a, b, c]; //The name of each button

for each(var index in items) {
    index.addEventListener(MouseEvent.CLICK, mouseClickHandler);
}

function mouseClickHandler(event:MouseEvent):void {
    trace(event.currentTarget.name); //Should display the name of any of the buttons clicked.
}
于 2012-11-05T03:07:11.240 回答
0

这里只index创建了一个变量——mouseClickHandler很明显,函数只使用它的当前值。如果您需要参考特定值(在每个循环步骤中给出),您需要以一种或另一种方式对它们进行本地化:

function generateClickHandler(index:someType) {
  return function(event:MouseEvent):void { trace(index.name); }
}

...    
for each(var index in items) 
{
    index.addEventListener(MouseEvent.CLICK, generateClickHandler(index);
}

我建议也检查这个线程

于 2012-11-04T16:13:59.780 回答