Javascript Event Listener on click not working as expected

前端 未结 5 427
感动是毒
感动是毒 2021-01-20 15:54

I\'m trying to create one event listener to handle all my \"clicks\" by putting it on the body and doing some event delegation. A simple example of what i\'m trying to do i

5条回答
  •  余生分开走
    2021-01-20 16:54

    There are two elements associated with an event:

    1. event.currentTarget, which is the element that is actually calling the listener (i.e. the on which the listener has been attached), and
    2. event.target, which is the element on which the event actually occurred

    These can be the same element, parent and child, or ancestor and descendant (which is the case here).

    So a click on an LI makes it the target, and since the body's click handler calls the listener, it's the currentTarget, the DIV is neither. If you put the listener on the DIV, it will then become the currentTarget.

    Originally, nodes other than elements could be event targets, but in recent implementations only elements are targets.

    Some links:

    1. W3C DOM 4 Interface eventTarget
    2. W3C DOM 4 Event

    Note that that target and eventTarget are specified as (host) objects, they aren't necessarily elements though that is how they are mostly implemented in current browsers.

提交回复
热议问题