Difference between e.target and e.currentTarget

后端 未结 10 1022
谎友^
谎友^ 2020-11-22 06:29

I don\'t understand the difference, they both seem the same but I guess they are not.

Any examples of when to use one or the other would be appreciated.

10条回答
  •  耶瑟儿~
    2020-11-22 06:49

    It's worth noting that event.target can be useful, for example, for using a single listener to trigger different actions. Let's say you have the typical "menu" sprite with 10 buttons inside, so instead of doing:

    menu.button1.addEventListener(MouseEvent.CLICK, doAction1);
    menu.button2.addEventListener(MouseEvent.CLICK, doAction2);
    etc...
    

    You can simply do:

    menu.addEventListener(MouseEvent.CLICK, doAction);
    

    And trigger a different action within doAction(event) depending on the event.target (using it's name property, etc...)

提交回复
热议问题