2010-01-08 53 views
1

我在Flash中创建了一个导航栏,并使用5个不同的影片剪辑作为按钮。每个动画片段(按钮)具有不同的实例名称。有没有办法使用的addEventListener让我没有做soemthing这样的:动态使用addEventListener?

//for button1 
button1.buttonMode = true;// Show the hand cursor 
button1.addEventListener(MouseEvent.ROLL_OVER, button1_over); 
button1.addEventListener(MouseEvent.ROLL_OUT, button1_out); 
button1.addEventListener(MouseEvent.CLICK, button1_click); 

function button1_over(e:MouseEvent):void 
{ 
    e.currentTarget.gotoAndPlay("over"); 
} 

function button1_out(e:MouseEvent):void 
{ 
    e.currentTarget.gotoAndPlay("out"); 
} 

function button1_click(e:MouseEvent):void 
{ 
    var request:URLRequest = new URLRequest("http://website.com"); 
    navigateToURL(request); 
} 
//for button2 
button2.buttonMode = true;// Show the hand cursor 
    button2.addEventListener(MouseEvent.ROLL_OVER, button2_over); 
    button2.addEventListener(MouseEvent.ROLL_OUT, button2_out); 
    button2.addEventListener(MouseEvent.CLICK, button2_click); 

    function button2_over(e:MouseEvent):void 
    { 
     e.currentTarget.gotoAndPlay("over"); 
    } 

    function button2_out(e:MouseEvent):void 
    { 
     e.currentTarget.gotoAndPlay("out"); 
    } 

    function button2_click(e:MouseEvent):void 
    { 
     var request:URLRequest = new URLRequest("http://website.com"); 
     navigateToURL(request); 
    } 

...等等所有五个按钮?

+0

大问题! thenduks回答如下,但作为一个附注......我发现我喜欢将“ROLL_OUT”监听器放在“ROLL_OVER”函数中。并删除它,以及ROLL_OUT – 2010-01-08 17:19:08

回答

5
function buttonOver(e:MouseEvent):void { 
    e.currentTarget.gotoAndPlay('over'); 
} 
... etc 

for each(var b:MovieClip in [button1,button2,button3,button4,button5]) { 
    b.addEventListener(MouseEvent.ROLL_OVER, buttonOver); 
    b.addEventListener(MouseEvent.ROLL_OUT, buttonOut); 
    b.addEventListener(MouseEvent.CLICK, buttonClick); 
} 

你甚至可以进一步拾遗在函数内部事件的类型提高它,只是有一个:

function buttonHandler(e:MouseEvent):void { 
    // see the docs for MouseEvent and figure 
    // out what string to pass to goToAndPlay 
} 
+0

button = movieclip – 2010-01-08 18:50:19

+0

对不起,这是不明显的,你试图添加监听器的对象类是什么。但是,是的,通过'button5'的任何类型'button1'都会进入'for each'。干杯! – rfunduk 2010-01-08 21:23:58