admin管理员组

文章数量:1240587

I have this code:

var x = document.getElementsByClassName("hex");
     
for(var i = 0; i < x.length; i++)
{
    x[i].addEventListener("click", myFunction);
}

To attach onclick dynamically. My question is myFunction how to get the clicked element?

I have this code:

var x = document.getElementsByClassName("hex");
     
for(var i = 0; i < x.length; i++)
{
    x[i].addEventListener("click", myFunction);
}

To attach onclick dynamically. My question is myFunction how to get the clicked element?

Share Improve this question edited Aug 25, 2021 at 18:19 Brian Tompsett - 汤莱恩 5,89372 gold badges61 silver badges133 bronze badges asked Sep 16, 2016 at 16:09 Mo.MesferMo.Mesfer 771 gold badge2 silver badges9 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 13

Let myFunction take in an argument (call it event). event.target is then the clicked element:

function myFunction(event) {
    var clickedElement = event.target;
    // Do important stuff with clickedElement.
}

本文标签: dom eventsJavaScript get the sender elementStack Overflow