JS get the clicked element with event.target

前端 未结 4 465
青春惊慌失措
青春惊慌失措 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条回答
  • 2021-01-28 13:42

    As I wrote in my comment event.target should be fine. But you should be careful if you really only want the p-tags. If you use a-tags or other child elements in the wrapping div you could potentially also receive other tags.

    I'd suggest to actually add the event listener to the p-tags directly.

    0 讨论(0)
  • 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
    })
    
    0 讨论(0)
  • 2021-01-28 13:49

    Probably best to attach the event listener to each of the p elements in case you have other children elements nested within the p element itself.

    const paragraphs = document.querySelectorAll("div > p");
    
    for (let i = 0; i < paragraphs.length; i += 1) {
      paragraphs[i].addEventListener("click", function (event) {
            console.log(event.currentTarget);
      });
    }
    
    0 讨论(0)
  • 2021-01-28 13:57

    If you use event.target you should get the specific p tag that you clicked.

    However, if you really want to use this, you're better off attaching the onclick event handler to the p tags themselves rather than the parent.

    Like so.

    let ps = document.getElementsByTagName('p')
    
    for (var i = 0; i < ps.length; ++i){
        ps[i].addEventListener('click', function(event){
            // how to get the clicked p tag here?
            alert(this.innerText) //or whatever action you want to do with `this`
       })
    }
    
    0 讨论(0)
提交回复
热议问题