简体   繁体   English

JS 通过 event.target 获取被点击的元素

[英]JS get the clicked element with event.target

I am trying to use JavaScript to get a clicked element's information.我正在尝试使用 JavaScript 获取点击元素的信息。

Here is the jsFiddle .这是jsFiddle

And below is my code.下面是我的代码。

 let div = document.querySelector('div') div.addEventListener('click', function(event) { // how to get the clicked p tag here? // this? // event.target.currentTarget? })
 <div> <p>text 1</p> <p>text 2</p> </div>

How can I use this to get the element's information?我如何使用this来获取元素的信息?

Answer: event.target Thanks Juan Mendes答案: event.target谢谢 Juan Mendes

Welcome to StackOverflow!欢迎来到 StackOverflow!

e.target should give you the exact element that was clicked to generate the event. e.target应该为您提供被点击以生成事件的确切元素。

e.currentTarget will give you the element that the event is at when the function was called (after bubbling up from the e.target ) e.currentTarget将为您提供调用函数时事件所在的元素(从e.target冒泡后)

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

As I wrote in my comment event.target should be fine.正如我在评论event.target中所写的那样应该没问题。 But you should be careful if you really only want the p-tags.但是如果你真的只想要 p-tags,你应该小心。 If you use a-tags or other child elements in the wrapping div you could potentially also receive other tags.如果您在包装 div 中使用 a-tags 或其他子元素,您可能还会收到其他标签。

I'd suggest to actually add the event listener to the p-tags directly.我建议直接将事件侦听器添加到 p-tags。

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.可能最好将事件侦听器附加到每个p元素,以防你有其他子元素嵌套在p元素本身中。

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);
  });
}

If you use event.target you should get the specific p tag that you clicked.如果你使用event.target你应该得到你点击的特定p标签。

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.但是,如果您真的想使用this ,最好将 onclick 事件处理程序附加到 p 标签本身而不是父标签。

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`
   })
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM