Flash AS3 if/else 语句未按预期工作

Flash AS3 if/else statement not working as expected

我试图在 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");

}

您在事件侦听器的功能执行后删除它:

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);
}

考虑你的前两行:

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,下次这段代码 运行s 时,您只需使用行 var myFlag:int=1.[= 将其设置回 1 15=]

您需要做的是将您的 myFlag var 和它的初始值移动到您的 if 语句范围的某处。

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

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

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


编辑

根据您的评论,您只需在点击按钮后将其删除。看代码注释

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);
}