我一直在尝试动态添加按钮,然后为它们分配事件侦听器。我的代码是,
var i=0;
var step=50;
for each (var child:XML in courseXML.footer.tray.elements())
{
var thumbClip:thumb = new thumb();
//set name
thumbClip.name = "mc_thumb" + (i + 1);
trace("thumbClipname:: "+thumbClip.name);
//set the x and y values
thumbClip.x = 620 + (i * step);
thumbClip.y = 560;
//attach the newly created instance to the container
addChild(thumbClip);
trace("thumbClip:: "+thumbClip);
//attach icon image from xml path
thumbClip.thumbLoader.source = child.icon;
trace("thumbClip.thumbLoader.source: "+thumbClip.thumbLoader.source);
//add listeners
trace("Node name "+ child.localName());
if(child.localName().toLowerCase() == "feedback");
{ trace("gotoFeedback..");
thumbClip.addEventListener(MouseEvent.CLICK, gotoFeedback);
}
if(child.localName().toLowerCase() == "resources");
{ trace("gotoResources..");
thumbClip.addEventListener(MouseEvent.CLICK, gotoResources);
}
if(child.localName().toLowerCase() == "glossary");
{ trace("gotoGlossary..");
thumbClip.addEventListener(MouseEvent.CLICK, gotoGlossary);
}
if(child.localName().toLowerCase() == "discussion");
{ trace("gotoDiscussion..");
thumbClip.addEventListener(MouseEvent.CLICK, gotoDiscussion);
}
thumbClip.buttonMode = true;
i++;
}
所以,最后在舞台上显示了4个按钮,当我点击任何按钮时,所有四个函数gotofeedback, gotoResources, gotoGlossary, gotoDiscussion
都会被调用。如何在按钮点击时调用相应的功能?谢谢!
The four functions are:
function gotoFeedback(e: MouseEvent):void
{
trace("gotofeedback fn called..");
}
function gotoResources(e: MouseEvent):void
{
trace("gotoResources fn called..");
}
function gotoGlossary(e: MouseEvent):void
{
trace("gotoGlossary fn called..");
}
function gotoDiscussion(e: MouseEvent):void
{
trace("gotoDiscussion fn called..");
}
答案 0 :(得分:0)
您需要将事件侦听器添加到子按钮,而不是添加到thumbClip。你现在拥有代码的方式,只要在thumbClip内的任何地方点击鼠标,就会调用所有的监听器(这就是你所看到的)。