AS3循环按钮(添加监听器和功能)

时间:2013-12-20 15:03:32

标签: actionscript-3 loops button listener

我如何进行循环,这样我就不必将相同的代码复制并粘贴到10或更高的位置?

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

1 个答案:

答案 0 :(得分: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);
}