简体   繁体   中英

Get ID of element clicked

<html>
<head>

<script type="text/javascript">
function getElement(e) {
    var element = e.target || e.srcElement;
    alert(element.id);
}
</script>

</head>
<body onclick="getElement()">

<div id="div1"></div>
<div id="div2"></div>

</body>
</html>

Tried this to get the ID of element clicked and alert it. I'm sure it's something pretty basic I'm missing.

Can anyone help?

It's actually pretty basic, stop using inline event handlers

<!DOCTYPE html>
    <head>
        <title>It works</title>
    </head>
    <body>

        <div id="div1"></div>
        <div id="div2"></div>

        <script type="text/javascript">
            document.addEventListener('click', function(e) {
                alert( e.target.id );
            }, false);
        </script>
    </body>
</html>

FIDDLE

In this particular case, you need to actually send in the event object when binding to the onclick handler (example below).

However, I would strongly advise against using this approach!

Use document.addEventListener instead.

 <html> <head> <script type="text/javascript"> function getElement(e) { var element = e.target || e.srcElement; alert(element.id); } </script> </head> <body onclick="getElement(event)"> <div id="div1">First Div</div> <div id="div2">Second Div</div> </body> </html> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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