Action Script 3. How to remove child which is created from another function?

依然范特西╮ 提交于 2019-12-12 01:43:08

问题


I have added child with function first, and I need to remove It with function third.

function first(event:MouseEvent):void {
   addChild(test); //here add child
   button.addEventListener(MouseEvent.CLICK, second); //here add listener to second function
}

    function second(event:MouseEvent):void {
       third(event); //here I call third function 
}

   private function third(event:Event):void {
       removeChild(test); //here should delete child, but I got error
}

But I got following error: ArgumentError: Error #2025: The supplied DisplayObject must be a child of the caller. How to remove child successfully? Could you help me, please? Thank you.


回答1:


There are two ways. First, keep a reference to the clip that you've add:

_private var clip:Sprite;

public function first():void {
    addChild(clip);
}

public function second():void {
    removeChild(clip);
}

Having the clip that you add/remove as a variable help you to use it in multiple functions. But if there is some problem with that - like not using classes and having code in multiple places, you can always use the name property:

public function first():void {
    var child:Sprite = new Sprite(); // create new instance so it's not visible anywhere
    child.name = 'myFancySprite';
    addChild(child);
}

public function second():void {
    var child:Sprite = getChildByName('myFancySprite') as Sprite; // get it
    removeChild(child); // remove it
}


来源:https://stackoverflow.com/questions/24040609/action-script-3-how-to-remove-child-which-is-created-from-another-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!