JS get the clicked element with event.target

前端 未结 4 470
青春惊慌失措
青春惊慌失措 2021-01-28 13:17

I am trying to use JavaScript to get a clicked element\'s information.

Here is the jsFiddle.

And below is my code.

4条回答
  •  旧时难觅i
    2021-01-28 13:43

    Welcome to StackOverflow!

    e.target should give you the exact element that was clicked to generate the event.

    e.currentTarget will give you the element that the event is at when the function was called (after bubbling up from the e.target)

    div.addEventListener('click', (e) => {
    console.log(e.target) // the p that was clicked
    console.log(e.currentTarget) // this div
    })
    

提交回复
热议问题