AS3 forlooping按钮和功能

时间:2012-08-20 15:21:15

标签: actionscript-3 for-loop

我正在学习Actionscript,我有点坚持循环。

我有这段代码,

movieClip.thumbnail1.addEventListener(MouseEvent.CLICK ,myBtn1);
function myBtn1(evt:MouseEvent):void
{

     var myMC:MC1 = new MC1();
     mcPlacement.addChild(myMC);
}

movieClip.thumbnail2.addEventListener(MouseEvent.CLICK ,myBtn2);
function myBtn2(evt:MouseEvent):void
{

     var myMC2:MC2 = new MC2();
     mcPlacement.addChild(myMC2);
}

我想知道,你如何使用for循环来叠加它们以便我可以运行10个按钮而不必输入很长的路,我是否应该使用数组呢?

1 个答案:

答案 0 :(得分:0)

如果movieClip仅包含您要为其添加事件侦听器的thumbNails,则可以执行以下操作:

private function addEventListeners():void
{
    for(var i=0; i<movieClip.numChildren; i++)
    {
        var dp:DisplayObject = movieClip.getChildByIndex(i) as DisplayObject;
        dp.addEventListener(MouseEvent.CLICK,onThumbNailClicked);
    }
}

private function onThumbNailClicked(e:MouseEvent):void
{
    trace("Clicked : "+e.target.name);

}

如果您事先知道缩略图的名称,可以在事件处理程序中创建不同的影片剪辑并将它们添加到mcPlacement。

private function onThumbNailClicked(e:MouseEvent):void
{
    var mcs:Object = {
        "thumbNail1":MC1,
        "thumbNail2":MC2
    };
    trace("Clicked : "+e.target.name);
    var mc:MovieClip = new mcs[e.target.name]();
    mcPlacement.addChild(mc);
}