addEventlistener,array,as linkage

时间:2014-01-20 04:01:57

标签: actionscript-3

我在此功能中添加了10个带有AS链接Box的动画片段。我已将不同的实例layer1命名为layer10

我的问题是,如何才能添加一个eventlistener,仅举几个layer4

var NUM_BOXES:int = 10;
var BOX_SPACING:int = 1;

var _boxes:Array = [];

function Test()
{
    for (var i:int = 0; i < NUM_BOXES; i++)
    {
        var box:Box = new Box( i + 1 );
        box.y = (box.height + BOX_SPACING) * i;
        box.name= "layer" +( i + 1);
        box.buttonMode = true;
        box.addEventListener( MouseEvent.MOUSE_DOWN, onBoxPress );
        box.addEventListener( MouseEvent.MOUSE_UP, onBoxRelease );
        addChild( box );
        _boxes.push( box );
    }
}

2 个答案:

答案 0 :(得分:1)

bluebill1049 的答案为基础:

if(number == 4)方法不可扩展,即如果您想要一百个图层拥有侦听器,则无法为每个图层编写if语句。简单的解决方案是:

var NUM_BOXES:int = 10;
var BOX_SPACING:int = 1;

var _boxes:Array = [];

//Any numbers in this array are assigned listeners
var layers_with_listeners:Array = [1, 4, 9]; 

function Test()
{
    for (var i:int = 0; i < NUM_BOXES; i++)
    {
        var box:Box = new Box( i + 1 );
        box.y = (box.height + BOX_SPACING) * i;
        box.name= "layer" +( i + 1);
        box.buttonMode = true;

        if(layers_with_listeners.indexOf(i+1) != -1) {     
            box.addEventListener( MouseEvent.MOUSE_DOWN, onBoxPress );
            box.addEventListener( MouseEvent.MOUSE_UP, onBoxRelease );
        }

        addChild( box );
        _boxes.push( box );
    }
}

答案 1 :(得分:0)

var NUM_BOXES:int = 10;
var BOX_SPACING:int = 1;

var _boxes:Array = [];
var number:int;

function Test()
{
    for (var i:int = 0; i < NUM_BOXES; i++)
    {
            number = i + 1;
            var box:Box = new Box(number);
            box.y = (box.height + BOX_SPACING) * i;
            box.name= "layer" +(number);
            box.buttonMode = true;

            if(number == 4)
            {
                box.addEventListener( MouseEvent.MOUSE_DOWN, onBoxPress );
                box.addEventListener( MouseEvent.MOUSE_UP, onBoxRelease );
            }


            addChild( box );
            _boxes.push( box );
    }
}