我有一个名为ary的数组和这个数组中的一些对象,它们是ary [0],ary [1],ary [2],ary [3]和ary [4]。每个都有一个文本属性我希望为ary中的所有元素添加一个eventListener,并将该属性传递给一个函数。首先,我按如下方式执行:
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)});
}
for above code,I got an error "TypeError: Error #1010: A term is undefined and has no properties.".Then I also try another way.
for(var i=0;i<arylength;i++){
ary[i].addEventListener(MouseEvent.CLICK,function(e:MouseEvent){toGo(e,ary[i].topname.text)});
}
它没有错误,但我得到的变量“namestr”始终是ary中最后一个元素的变量。为什么呢?
我在哪里弄错了?
感谢。
答案 0 :(得分:1)
你的第一个for循环,错误是ary和length之间的缺失时间。您有arylength
,但应该是ary.length
。
更好的方法是:(不使用匿名函数,使用事件的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.