JS get the clicked element with event.target

前端 未结 4 466
青春惊慌失措
青春惊慌失措 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: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`
       })
    }
    

提交回复
热议问题