1

我有一个包含许多图像的容器。我不想在每个图像上添加单击和其他鼠标事件的侦听器,而是只想在图像的父级上侦听这些事件。

那可能吗?

4

2 回答 2

7
container.addEventListener(MouseEvent.CLICK, clickHandler);
private function clickHandler(e:MouseEvent):void {
  trace(e.currentTarget); // references container
  trace(e.target); //references container's child or container itself depending on what has been clicked 
}
于 2012-01-10T14:29:10.663 回答
1

如果我正确理解您的问题,那是完全有可能的。所以假设你有类似的东西:

parent.addChild(new Child());
parent.addChild(new Child());
parent.addChild(new Child());
parent.addChild(new Child());

然后您应该能够将事件侦听器绑定到父级:

parent.addEventListener(MouseEvent.CLICK, handleClick);

然后你的处理程序应该看起来像

private function handleClick(e:MouseEvent) {
    // cast the target of the event as the correct class
    var clickedChild:Child = Child(e.target); 

    // Do whatever you want to do.
}

您还可以将它与useCaptureaddEventListener 的参数结合起来,将事件附加到事件的捕获端而不是冒泡端。并且还使用.stopPropagation()Event 上的方法来阻止任何其他事件处理程序触发......

但是很难说你是否需要在不知道更多关于你想要做什么的情况下使用它们。但希望这会让你朝着正确的方向前进。

于 2012-01-10T14:31:24.390 回答