我对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循环中的最后一个元素(差异),所以我只能删除最后一个eventlistener。我希望能够为每个元素删除eventlisteners。
你能帮我解决这个问题吗?谢谢!
答案 0 :(得分: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();
}
答案 1 :(得分: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);
}