尝试在actionscript上创建按钮:创建和删除movieclip对象,但总是出现一些错误...... 我需要一个按钮创建movieclip,另一个必须通过鼠标单击删除它。这是代码:
import flash.events.MouseEvent;
import flash.display.MovieClip;
import flash.text.TextField;
main.addEventListener(MouseEvent.CLICK, addMain);
function addMain(e: MouseEvent) {
var movieClip: bm = new bm();
movieClip.x = 640;
movieClip.y = 570;
this.addChild(movieClip);
main.removeEventListener(MouseEvent.CLICK, addMain);
deletemain.removeEventListener(MouseEvent.CLICK, addMain);
}
deletemain.addEventListener(MouseEvent.CLICK, deleteMain);
function deleteMain(e: MouseEvent) {
var movieClip: bm = bm(event.target);
this.removeChild(movieClip);
removeChild(movieClip);
movieClip = null;
deletemain.removeEventListener(MouseEvent.CLICK, deleteMain);
}
答案 0 :(得分:0)
好的,要了解您的代码无效的原因,让我们来看看它:
main.addEventListener(MouseEvent.CLICK, addMain);
function addMain(e: MouseEvent)
{
// here you are creating a local var "movieClip"
// inside your "addMain" function, so it's only accessible here
var movieClip:bm = new bm();
movieClip.x = 640;
movieClip.y = 570;
this.addChild(movieClip);
main.removeEventListener(MouseEvent.CLICK, addMain);
// I don't really know why you do this !
deletemain.removeEventListener(MouseEvent.CLICK, addMain);
}
deletemain.addEventListener(MouseEvent.CLICK, deleteMain);
function deleteMain(e: MouseEvent)
{
// here, you are creating a local var "movieClip"
// by casting (converting) your "deletemain" button (e.target) to an "bm" object
// event.target should be e.target
var movieClip: bm = bm(event.target);
// here your are removing the "deletemain" button, once
this.removeChild(movieClip);
// and twice
removeChild(movieClip);
movieClip = null;
deletemain.removeEventListener(MouseEvent.CLICK, deleteMain);
}
所以要做你想做的事:创建一个MovieClip并使用两个按钮删除它,你必须声明你的" movieClip"作为两个侦听器函数可访问的全局变量:
// declare a global "bm" object
var movieClip:bm;
btn_add.addEventListener(MouseEvent.CLICK, btn_add_onPress);
function btn_add_onPress(e: MouseEvent): void
{
// create the "movieClip" object
movieClip = new bm();
addChild(movieClip);
// remove the click event listener for the btn_add
btn_add.removeEventListener(MouseEvent.CLICK, btn_add_onPress);
}
btn_delete.addEventListener(MouseEvent.CLICK, btn_delete_onPress);
function btn_delete_onPress(e:MouseEvent) : void
{
// remove the "movieClip" object
removeChild(movieClip);
movieClip = null;
// remove the click event listener for the btn_delete
btn_delete.removeEventListener(MouseEvent.CLICK, btn_delete_onPress);
}
希望可以提供帮助。