2013-12-20 73 views
1

我該如何去循環這個,所以我不必複製和粘貼相同的代碼高達10或更高?AS3循環按鈕(添加監聽器和功能)

optionsmenu.char01.addEventListener(MouseEvent.CLICK, gochar01); 
function gochar1 (event:MouseEvent): void { 
    char.gotoAndStop(1); 
} 
optionsmenu.char02.addEventListener(MouseEvent.CLICK, gochar02); 
function gochar2 (event:MouseEvent): void { 
    char.gotoAndStop(2); 
} 

回答

2

你可以嘗試這樣的事情:

var callbackGenerator:Function = function(i:int):Function { 
    return function(event:MouseEvent):void { 
    char.gotoAndStop(i); 
    }; 
}; 

// Change this according to size of your menu 
var menuSize:int = 12; 

for (var i:int = 1; i < menuSize; i++) { 
    // Prefix with 0 
    var index:String = i < 10 ? '0' + i : String(i); 

    // Generate the click callback 
    var callback:Function = callbackGenerator(i); 

    // Add the click event listener 
    optionsmenu['char' + index].addEventListener(MouseEvent.CLICK, callback); 
} 
+0

這工作,太感謝你了! – user3123073