【问题标题】:pass the variable to a function for objects in one array将变量传递给一个数组中对象的函数
【发布时间】:2015-07-02 12:06:55
【问题描述】:

我有一个名为 ary 的数组和这个数组中的一些对象,即 ary[0]、ary[1]、ary[2]、ary[3] 和 ary[4]。每个都有一个 text 属性element.我想为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){ ...... }

它确实有效。但是当我在 for(...){...} 中更改它时,它有一个错误。

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

对于上面的代码,我得到一个错误“TypeError: Error #1010: A term is undefined and has no properties.”。然后我也尝试了另一种方式。

for(var i=0;i

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

我在哪里犯错了?

谢谢。

【问题讨论】:

    标签: actionscript-3 flash


    【解决方案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.
    

    【讨论】:

    • 对不起“arylength”,这只是我的错字。我用你的方式来更正我的代码,然后它确实有效。非常感谢。除了一行function itemClick(e:Event):void {,应该是function itemClick(e:MouseEvent):void {
    • MouseEvent 扩展了事件,所以两者都可以,除非你真的想使用特定于 MouseEvent 的任何属性,然后是的,你会希望它是鼠标事件。
    猜你喜欢
    • 2020-07-28
    • 2017-06-10
    • 2018-01-20
    • 1970-01-01
    • 2014-04-02
    • 2020-12-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多