【问题标题】:Trying to remove child with mouseclick试图用鼠标点击删除孩子
【发布时间】:2013-07-24 01:26:15
【问题描述】:

所以,我的问题如下。

为什么会出现这个错误

(TypeError: 错误 #2007: 参数 child 必须为非空。 在 flash.display::DisplayObjectContainer/removeChild() 在 TargetMain/killTarget())

尝试通过鼠标单击从舞台上移除对象时?

我的应用程序代码如下。

package
{
    import flash.display.*;
    import flash.events.*;
    import flash.text.*;
    import flash.ui.Keyboard;

    public class TargetMain extends MovieClip
    {
        public function TargetMain()
        {
            stage.addEventListener(KeyboardEvent.KEY_DOWN, spawner);//Spawning function listener

            stage.addEventListener(MouseEvent.CLICK, killTarget);//Clicking function listener
        }

        public function spawner(k:KeyboardEvent):void
        {
            if(k.keyCode == 32)
            {
                trace ("spawned");
                var theTarget:ParaspriteFull = new ParaspriteFull();

                theTarget.x = Math.floor(Math.random() * stage.stageWidth);
                theTarget.y = Math.floor(Math.random() * stage.stageHeight);
                addChild(theTarget);

            }
        }

        public function killTarget(toDie:MouseEvent):void
        {
            trace ("clicked")
            var deadTarget:ParaspriteFull = (toDie.target as ParaspriteFull);
            //Below is where I continually get an error and do not know how to fix it.
            //This is also after searching the internet for hours trying to solve my issue.

            //MovieClip(deadTarget).parent.removeChild(deadTarget);
            removeChild(deadTarget);
        }
    }
}

非常感谢任何帮助。

【问题讨论】:

    标签: actionscript-3 removechild addchild displayobject


    【解决方案1】:

    这个错误意味着 deadTarget 为空,所以如果你只是想从 stage 中删除 deadTarget,试试这个

     var deadTarget:DisplayObject = toDie.target as DisplayObject;
    
     if ( deadTarget && deadTarget.parent) {
         deadTarget.parent.removeChild(deadTarget);
     }
    

    或者你应该找出 deadTarget 的实际类型。

    【讨论】:

      【解决方案2】:

      您正在收听舞台上的点击。因此,任何点击(无论是否在 ParaspriteFull 对象上)都会触发killTarget。避免异常的一种方法是按照 Pan 在答案中的建议,如果单击的对象不是 ParaspriteFull 类型,则在单击 killTarget 中基本上什么都不做。 但是,我建议收听 ParaspriteFull 对象上的点击,而不是在舞台上。即删除

      stage.addEventListener(MouseEvent.CLICK, killTarget);//Clicking function listener
      

      从您的 constructor 并修改 spawner 函数以将点击侦听器添加为:

      theTarget.addEventListener(MouseEvent.CLICK, killTarget);//Clicking function listener
      

      另外,删除 killTarget 中 ParaspriteFull 对象上的侦听器:

      deadTarget.removeEventListener(MouseEvent.CLICK, killTarget);//Remove clicking function listener
      

      【讨论】:

        猜你喜欢
        • 2015-10-24
        • 1970-01-01
        • 2015-07-29
        • 1970-01-01
        • 2011-01-28
        • 1970-01-01
        • 1970-01-01
        • 2019-01-04
        • 2012-09-12
        相关资源
        最近更新 更多