【问题标题】:Flash AS3 if/else statement not working as expectedFlash AS3 if/else 语句未按预期工作
【发布时间】:2015-04-10 21:08:20
【问题描述】:

我正在尝试在 Flash AS3 中执行此代码,但无法正常工作。在我的If 条件的主体中,我设置了myFlag = 2,但if 条件始终为True!!

这是我的代码:

var myFlag:int = 1;
if (myFlag==1)
{
    s1.addEventListener(MouseEvent.MOUSE_UP,dars1);
    function dars1(e:MouseEvent):void
    {
        myFlag= 2;
        s1.gotoAndStop(25);
        s1.mouseEnabled = false;
        var darsRequest:URLRequest = new URLRequest("dars1.swf");
        var darsLoader:Loader = new Loader();
        darsLoader.load(darsRequest);
        addChild(darsLoader);
    }

}
else
{
    trace("NO-CLICK");

}

【问题讨论】:

  • 当 flag = 1 时,您设置了一个事件侦听器...之后即使 flag 等于 2,侦听器仍然存在并且仍然会在 mouseup 时触发 dars1...您不这么认为吗?
  • 正如 JBA 所写:您的事件侦听器已添加。您没有在事件侦听器中检查条件 - 您应该。
  • 您找到解决方案了吗?为有帮助的答案投票,如果它导致您的解决方案,请接受答案。如果您的解决方案不同,请自己回答问题并接受。

标签: actionscript-3 flash flash-cs6


【解决方案1】:

考虑你的前两行:

var myFlag:int = 1;  //You are setting the var to 1
if (myFlag==1) //Since you just set it to 1 on the preceding line, this will ALWAYS be true
{

即使您在 if 语句中设置了 myFlag,下次运行此代码块时,您也只需使用行 var myFlag:int=1 将其设置回 1。

您需要做的是将您的 myFlag var 及其初始值移动到 if 语句范围的某个位置。

由于您没有说明发布的代码在哪里运行(主时间线?进入帧处理程序?鼠标按下处理程序?影片剪辑时间线?),因此很难具体提供帮助。

如果它是主时间线,那么代码无论如何只会运行一次,所以有一个标志没有意义。

如果是鼠标或进入帧事件处理程序,则将var myFlag:int=1 移动到主时间线并移出该事件处理程序。


编辑

根据您的评论,您只需在单击按钮后将其删除。见代码cmets

s1.addEventListener(MouseEvent.MOUSE_UP,dars1,false,0,true); //best to use a few more parameters and make it a weak listener
function dars1(e:MouseEvent):void
{
    //load you swf
    var darsRequest:URLRequest = new URLRequest("dars1.swf");
    var darsLoader:Loader = new Loader();
    darsLoader.load(darsRequest);
    addChild(darsLoader);

    if(s1.parent) s1.parent.removeChild(s1); //if you want the button totally gone from the stage

    //or if your gotoAndStop(25) does something along the lines of not showing the button, keep that:

    s1.gotoAndStop(25);
    s1.mouseEnabled = false;
    s1.mouseChildren - false; //you might need this too

    //or remove the listener so the button doesn't dispatch a mouse up anymore
    s1.removeEventListener(MouseEvent.MOUSE_UP, dars1,false);
}

【讨论】:

  • 为了获得更好的帮助/答案,请说明您发布的代码与您的应用程序相关的位置,以及您要在应用程序中完成的工作
  • 感谢大家的快速回复。我想通过单击按钮然后禁用按钮加载外部 swf 1 次。现在我该怎么办???
【解决方案2】:

你在函数执行后移除事件监听器:

s1.addEventListener(MouseEvent.MOUSE_UP,dars1);
function dars1(e:MouseEvent):void
{
    myFlag= 2;
    s1.gotoAndStop(25);
    s1.mouseEnabled = false;
    var darsRequest:URLRequest = new URLRequest("dars1.swf");
    var darsLoader:Loader = new Loader();
    darsLoader.load(darsRequest);
    addChild(darsLoader);
    s1.removeEventListener(MouseEvent.MOUSE_UP,dars1);
}

【讨论】:

  • 感谢大家的快速回复。我想通过单击按钮然后禁用按钮加载外部 swf 1 次。现在我该怎么办???
  • @MohammadDavarpanah 啊...请查看我的更新答案。
猜你喜欢
  • 2020-11-28
  • 2020-03-11
  • 1970-01-01
  • 2016-12-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-26
  • 2022-11-20
相关资源
最近更新 更多