2012-04-11 122 views
1

我有按鈕的列表:AS3陣列按鈕嵌套

agreeButton disagreeButton container.clickButton1 container.clickButton2

Container是另一個影片剪輯和它裏面是最後的2個按鈕。

我該如何把它放在數組中,並將所有相同的監聽器應用到它們中的每一個?

var buttonArray:Array = new Array("agreeButton", "disagreeButton", "container.clickButton1", "container.clickButton2"); 
for (var i:int=0; i<buttonArray.length; i++) { 
    this[buttonArray[i]].addEventListener(MouseEvent.ROLL_OVER, mouseRollOver); 
    this[buttonArray[i]].addEventListener(MouseEvent.ROLL_OUT, mouseRollOut); 
    this[buttonArray[i]].addEventListener(MouseEvent.CLICK, mouseClick); 
} 

回答

2

保留對按鈕的引用並將它們添加到數組中。

var agreeButton:Button = new Button(); 
var disagreeButton:Button = new Button(); 

//... Code that will add the above instantiated buttons to the canvas 

var buttonArray:Array = new Array(agreeButton, disagreeButton); 

for (var i:int = 0; i < buttonArray.length; i++) {  
buttonArray[i].addEventListener(MouseEvent.CLICK, mouseClick); 
} 


private function mouseClick(event:MouseEvent):void { 
    Alert.show("Boom!"); 
} 
+0

的簡單例子,非常感謝! – Anderson 2012-04-11 16:05:32

+0

只是一個簡單的問題,那麼「container.clickButton1」,「container.clickButton2」按鈕呢?他們在名爲「容器」的動畫片段中。你如何在動畫片段中聲明變量? – Anderson 2012-04-11 16:08:47

+0

另外我用SimpleButton代替。 – Anderson 2012-04-11 16:10:46

1

我會做一個button類,每個這些按鈕擴展。在按鈕類中添加eventListeners

例子:

原諒我,如果有事情不對的,我沒有在AS3編碼了一段時間。

class MyButton extends Button 
{ 
    public function MyButton() 
    { 
     this.addEventListener(MouseEvent.ROLL_OVER, mouseRollOver); 
     this.addEventListener(MouseEvent.ROLL_OUT, mouseRollOut); 
     this.addEventListener(MouseEvent.CLICK, mouseClick); 
    } 
    //... Add mouseRollOver, mouseRollOut, mouseClick methods 
} 

你各個按鈕

class DisagreeButton extends MyButton 
{ 
    public function DisagreeButton() 
    { 

    } 
} 

class AgreeButton extends MyButton 
{ 
    public function AgreeButton() 
    { 

    } 
} 

一旦你實例化所有的事件監聽器將被應用到每個按鈕。

+0

你能舉個例子嗎? – Anderson 2012-04-11 15:55:25

+0

@Anderson我加了一個我所指的 – brenjt 2012-04-11 16:42:03