문제

I'm getting an odd behavior with my "mouseup" event. I have a div inside a div. The mouseup event is attached to the OUTER div, yet if I happen to click on the INNER div, the e.target is set to the child div instead of the parent div that has the event.

Is this normal?

<div class="parent">
    <div class="child"></div>
</div>

So a:

$("body").on('mouseup', '.parent',myMethod);

Reports an e.target as child if it's exactly clicked.

도움이 되었습니까?

해결책

Notice the difference between .target and .currentTarget

This property of event objects is the object the event was dispatched on. It is different than event.currentTarget when the event handler is called in bubbling or capturing phase of the event.

  • event.target // A reference to the target to which the event was originally dispatched.
  • event.currentTarget // A reference to the currently registered target for the event.

Worth testing:

$("body").on('mouseup', '#parent1', function (e) {
    console.log(e.target,e.currentTarget);
});

Demo jQuery
Demo plain javascript


More reading:

MDN: event.target
MDN: event
jQuery (an explanation about Direct and delegated events)

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top