Actionscript - Adding EventListener to multiple bu

2019-08-21 20:27发布

问题:

I have a little problem with adding EventListener to multiple objects on stage. I have above 40 buttons on stage named "Button01","Button02" .. "Button40", and i'm looking for easiest way to add EventListener to all of them.

Creating something like

Button01.addEventListener(MouseEvent.CLICK, doSomething)
Button02.addEventListener(MouseEvent.CLICK, doSomething)
..
Button40.addEventListener(MouseEvent.Click, doSomething)

(Notice the same function). isn't solution i'm looking for :(.

Thanks in advance.

回答1:

You could do something like this:

var cnt:Number;
var cnt_str:String;
for (cnt = 1; cnt <= 40; cnt++) {
    if (cnt < 10) {
        cnt_str = "0" + String(cnt);
    } else {
        cnt_str = String(cnt);
    }
    this["Button" + cnt_str].addEventListener(MouseEvent.CLICK, doSomething);
}

This assumes that this code is in the DocumentClass, or on your timeline somewhere since it is using this to access the MovieClips. If that is not the case then just replace the this with a reference of the container.