Difference between e.target and e.currentTarget

后端 未结 10 902
谎友^
谎友^ 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:36

    e.currentTarget is always the element the event is actually bound do. e.target is the element the event originated from, so e.target could be a child of e.currentTarget, or e.target could be === e.currentTarget, depending on how your markup is structured.

    0 讨论(0)
  • 2020-11-22 06:40
    target  is the element that triggered the event (e.g., the user clicked on)
    
    currenttarget is the element that the event listener is attached to.
    
    0 讨论(0)
  • 2020-11-22 06:41
    • e.target is element, which you f.e. click
    • e.currentTarget is element with added event listener.

    If you click on child element of button, its better to use currentTarget to detect buttons attributes, in CH its sometimes problem to use e.target.

    0 讨论(0)
  • 2020-11-22 06:43

    I like visual answers.

    When you click #btn, two event handlers get called and they output what you see in the picture.

    Demo here: https://jsfiddle.net/ujhe1key/

    0 讨论(0)
  • 2020-11-22 06:45

    e.target is what triggers the event dispatcher to trigger and e.currentTarget is what you assigned your listener to.

    0 讨论(0)
  • 2020-11-22 06:45

    make an example:

    var body = document.body,
        btn = document.getElementById( 'id' );
    body.addEventListener( 'click', function( event ) {
        console.log( event.currentTarget === body );
        console.log( event.target === btn );
    }, false );
    

    when you click 'btn', and 'true' and 'true' will be appeared!

    0 讨论(0)
提交回复
热议问题