循环遍历 Flex 中元素内的元素 [英] Looping over elements inside an element in Flex

查看:25
本文介绍了循环遍历 Flex 中元素内的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Flex 4 中有以下功能:

I have the following function in Flex 4:

protected function initEventHandlers():void
        {
            imageContainer.addEventListener(DragEvent.DRAG_ENTER, acceptDrag);
            imageContainer.addEventListener(DragEvent.DRAG_DROP, handleDrop);

            img_1.addEventListener(MouseEvent.MOUSE_DOWN, handleDrag);
            img_2.addEventListener(MouseEvent.MOUSE_DOWN, handleDrag);
            img_3.addEventListener(MouseEvent.MOUSE_DOWN, handleDrag);
            img_4.addEventListener(MouseEvent.MOUSE_DOWN, handleDrag);
        }

虽然我不喜欢这段代码的外观.这四个图像在我的应用程序中声明如下:

I didn't like the look of this code though. The four images are declared inside my application as follows:

<s:HGroup y="10" width="650" horizontalAlign="center" horizontalCenter="6">
        <s:Image width="80" height="80" source="images/1.jpg" id="img_1" />     
        <s:Image width="80" height="80" source="images/2.jpg" id="img_2" />
        <s:Image width="80" height="80" source="images/3.jpeg" id="img_3" />
        <s:Image width="80" height="80" source="images/4.jpg" id="img_4" />
</s:HGroup>

有没有办法遍历 hgroup 中的每个图像并添加事件处理程序?

Isn't there a way to loop over each image in the hgroup and add the eventhandler?

像这样:

for(image in hgroup) { 
    image.addEventlistener(MouseEvent.MOUSE_DOWN, handleDrag); 

}

我的老师告诉我这是不可能的,但在 10 多张图片的情况下,我无法想象对每张图片都单独进行.必须有更好的方法来做到这一点,不是吗?

 My teacher told me this isn't possible but in case of 10+ images, I can't imagine doing it for every image separately. There has to be a better way to do this, no?

提前致谢!

推荐答案

你的老师错了!

给 HGroup 一个 id(例如 imageGroup).

Give the HGroup an id (e.g. imageGroup).

然后这样做:

var numElements:int = imageGroup.numElements;
for (var i:int = 0; i<numElements; i++) {
    var image:Image= imageGroup.getElementAt(i) as Image;
    if (image) image.addEventlistener(MouseEvent.MOUSE_DOWN, handleDrag); 
}

这篇关于循环遍历 Flex 中元素内的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆