2015-04-03 27 views
0

我一直在嘗試動態添加按鈕,然後將事件監聽器分配給它們。對於這我的代碼,動作腳本:在按鈕單擊時調用相應的函數

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.."); 
} 
+1

你的gotoFeedback,gotoResources等函數在哪裏定義? – Barett 2015-04-03 18:28:54

+0

您將不得不顯示更多信息來診斷此問題。正如Barett指出的那樣,顯示你的'goto'命名函數的代碼。另外,你使用trace語句做了一些簡單的調試嗎?如果你的調試技能仍然需要改進,這總是找出問題的最簡單方法。 ;) – 2015-04-04 02:03:47

回答

0

您需要將事件偵聽器添加到子按鈕,而不是添加到thumbClip。現在你有了你的代碼,只要在thumbClip中的任何地方點擊鼠標,所有的監聽器都會被調用(這就是你所看到的)。

+0

聽起來像每個'thumbClip'都是單個按鈕,但由於某些原因,如果在時間軸上引用可能未正確設置的東西,則所有四個goto函數都正在執行。 – 2015-04-04 02:00:40

+0

好點 - 我衝我閱讀代碼。對事件添加跟蹤targetcurrentTarget可能很有啓發性 – 2015-04-06 15:11:33