问题
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