使用removeChild删除动态添加的MovieClip(未定义属性错误)

时间:2011-02-11 16:36:42

标签: actionscript-3 flash

我正在尝试删除动态创建的影片剪辑,导出时出现错误

  

1120:访问未定义的属性player_mc

function addplayer(id:String):MovieClip {
    var mcObj:Object=null;
    mcObj=getDefinitionByName(id.toString());
    return (new mcObj()) as MovieClip;
}
// this creates the mc
function startplayer():void {
    var player_mc:MovieClip = addplayer("s"+station.value);
    addChild(player_mc)
}
// this is supposed to remove it
function stopplayer():void {
    //the following line causes the error
    removeChild(player_mc);
}

正如您所看到的,我在我的库中使用addChild作为Movie Clip,这可以是类名为s1,s2,s3的库项目......

我尝试使用removechild(getchildbyname(?????));没有成功。如何删除导出时不存在的影片剪辑?

5 个答案:

答案 0 :(得分:2)

如果您不想将player_mc声明为全局变量,并且总是,则添加的最后一个子项可以使用removeChildAt(numChildren - 1)

答案 1 :(得分:0)

尝试在代码之上将player_mc声明为“全局变量”,而不是在函数startplayer()中声明。比它应该可以在stoporch()

内访问
var player_mc:MovieClip;

function addplayer(id:String):MovieClip {
    var mcObj:Object=null;
    mcObj=getDefinitionByName(id.toString());
    return (new mcObj()) as MovieClip;
}
//this creates the mc
function startplayer():void {
    player_mc = addplayer("s"+station.value);
    addChild(player_mc)
}
//this is supposed to remove it
function stoporch():void {
    //the following line causes the error
    removeChild(player_mc);
}

答案 2 :(得分:0)

您的stoporch函数正在引用不在范围内的变量player_mc。它被定义为startplayer中的本地。

您需要在stoporch可以看到它的位置保存引用,或者在添加时设置name属性,然后在删除它时使用getChildByName

答案 3 :(得分:0)

你的player_mc变量是在本地定义的,这意味着当函数startplayer()完成时它会消失。

您可以在函数之外创建一个类变量:

private var _player_mc : MovieClip;

并在你的函数中创建它:

_player_mc = addplayer("s"+station.value);

删除它,只需使用:

removeChild(_player_mc);

答案 4 :(得分:0)

存在一些选择。像其他人所说的那样,在班级创建变量是有效的。另一种方法是在剪辑制作后为剪辑指定名称。

function startplayer():void {
    player_mc = addplayer("s"+station.value);
    player_mc.name = "playerMC";
    addChild(player_mc)
    removeChild(this.getChildByName("playerMC"));
}
相关问题