1

我对 Actionscript 3 还很陌生,我有一个问题要问。我正在做一个相当简单的发现差异游戏,并且我正在将事件侦听器添加到 for 循环中的可点击差异。我的目标是,在我单击差异后,它也会删除其事件侦听器。

这是我的代码:

function addDifferences()
{
    for (var i = 1; i < 4; i++)
    {
        var difference = level1_left["level1_left_diff" + i];
        difference.alpha = 0;
        difference.addEventListener(MouseEvent.CLICK, onDifferenceClick);

        function onDifferenceClick(evt:Event):void
        {
            evt.currentTarget.alpha = 1;
            evt.currentTarget.play();
            found++;
            evt.currentTarget.removeEventListener(MouseEvent.CLICK, onDifferenceClick);
        }
    }
}

问题是我只能访问for循环中的最后一个元素(差异),所以我只能删除最后一个事件监听器。我希望能够删除每个元素的事件监听器。

你能帮我解决这个问题吗?谢谢!

4

2 回答 2

2

您应该将元素存储在一个数组中,以后可以循环使用。

var differences:Array = new Array(); //Class variable, or global if you don't use classes

function addDifferences()
{
    for (var i = 1; i < 4; i++)
    {
        var difference = level1_left["level1_left_diff" + i];
        difference.alpha = 0;
        difference.addEventListener(MouseEvent.CLICK, onDifferenceClick);

        differences.push(difference);
    }
}

//Don't create this function four time
function onDifferenceClick(evt:Event):void
{
    evt.currentTarget.alpha = 1;
    evt.currentTarget.play();
    found++;

    for (var i = 0; i < differences.length; i++)
    {
        differences[i].removeEventListener(MouseEvent.CLICK, onDifferenceClick);
    }

    //You can empty array afterwars, if you wish to start a new round (with addDifferences)
    differences = new Array();
}
于 2012-10-02T11:50:02.050 回答
0

您实际上并不需要将所有项目推入一个数组。您需要做的就是将正确的函数传递给 removeEventListener。在您的代码中,每次调用 removeEventListener 都会获取最后分配的内联函数。只需创建一个非内联函数,如:

function addDifferences()
{
    for (var i = 1; i < 4; i++)
    {
        var difference = level1_left["level1_left_diff" + i];
        difference.alpha = 0;
        difference.addEventListener(MouseEvent.CLICK, onDifferenceClick);
    }
}

function onDifferenceClick(evt:Event):void
{
    evt.currentTarget.alpha = 1;
    evt.currentTarget.play();
    found++; //assuming this is a global variable accessible from this function!!!
    evt.currentTarget.removeEventListener(MouseEvent.CLICK, onDifferenceClick);
}
于 2012-10-02T20:05:20.687 回答