2012-11-04 50 views
0

我想創建一個系統,顯示您按下的按鈕的名稱。 按鈕名稱被放入數組中,但它只識別輸入到數組中的最後一項。 幫助將不勝感激。AS3「爲每個」陣列問題

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. 

} 

回答

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); 
} 

我建議選中此thread爲好。

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. 
}