Looping over elements inside an element in Flex

浪子不回头ぞ 提交于 2019-12-11 03:42:02

问题


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>

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

Something like this:

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

}

 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?

Thanks in advance!


回答1:


Your teacher is wrong!

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

Then do this:

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); 
}


来源:https://stackoverflow.com/questions/7851875/looping-over-elements-inside-an-element-in-flex

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!