2015-04-24 46 views
0

我有一个名为ary的数组,这个数组中的一些对象是ary [0],ary [1],ary [2],ary [3]和ary [4]。还有在每一个element.I text属性希望将财产首先添加的事件监听在元的所有元素,并传递到function.At,我这样做如下:将变量传递给一个数组中的对象的函数

 
    ary[0].addEventListener(MouseEvent.CLICK,function(e:MouseEvent){toGo(e,ary[0].topname.text)}); 
    ary[1].addEventListener(MouseEvent.CLICK,function(e:MouseEvent){toGo(e,ary[1].topname.text)}); 
    ary[2].addEventListener(MouseEvent.CLICK,function(e:MouseEvent){toGo(e,ary[2].topname.text)}); 
    ary[3].addEventListener(MouseEvent.CLICK,function(e:MouseEvent){toGo(e,ary[3].topname.text)}); 
    ary[4].addEventListener(MouseEvent.CLICK,function(e:MouseEvent){toGo(e,ary[4].topname.text)});

function toGo(e:MouseEvent,str:String){ ...... }

it does work.But when I change it in for(...){...},it has an error.

for(var i=0;i<arylength;i++){ ary[i].addEventListener(MouseEvent.CLICK,function(e:MouseEvent){toGo(e,ary[i].topname.text)}); }

对于上面的代码,我得到一个错误“TypeError:Error#1010:一个术语是未定义的,没有任何属性。”然后我也尝试另一种方式。

for(var i = 0; i < ary.length; i ++){ namestr = ary [i] .topname.text; ary [i] .addEventListener(MouseEvent.CLICK,function(e:MouseEvent){toGo(e,namestr)}); }

它没有错误,但我得到的变量“namestr”始终是ary中最后一个元素的变量。为什么?

我在哪里犯了错误?

谢谢。

回答

1

您的第一个for循环,错误是ary和长度之间的缺失期。您有arylength,但它应该是ary.length

一个更好的方式来做到这将是以下几点:(不使用annonymous功能,使用事件的currentTarget属性来找出哪些项目是点击)

for(var i=0; i < ary.length; i++){ 
    ary[i].addEventListener(MouseEvent.CLICK,itemClick,false,0,true); 
} 

function itemClick(e:Event):void { 
    toGo(e, Object(e.currentTarget).topname.text; 
    //replace the object cast with whatever type your ary items are 
} 

//or even better, just go right to the toGo function and figure out the item clicked there. 
+0

对不起“arylength”,这只是我的错字。我用你的方式来纠正我的代码,然后它确实工作。除了一行'function itemClick(e:Event):void {',它应该是'function itemClick(e:MouseEvent):void {'。 –

+0

MouseEvent扩展了Event,所以或者没关系,除非你真的想使用MouseEvent特有的任何属性,那么是的,你会希望它是鼠标事件。 – BadFeelingAboutThis

相关问题