JavaScript: Get an item with a click

I need to get the clicked element in the getClickedElement function. How can i do this?

<html>
<head>
  <script>
    function getClickedElement () {
    }
  </script>
</head>
<body>
  <a href="javascript:alert(getClickedElement())" id="test">click me!!!</a>
</body>
</html>

I can only set the href attribute. I cannot set the onclick event because these elements are generated by a third party lib.

Thank.

+5
source share
4 answers

You cannot get an item with a click in the URL javascript:. The event has already ended, so no event.target(or window.event.srcElementfor IE), and javascript:links are not called using thisset (so you get window).

Of course, if you know that this link matters id="test", you can do it document.getElementById('test'), but I suspect you are missing the point of what you want to do.

href. onclick, lib.

lib. javascript: URL- - , .

<script> ? , click () . :.

for (var i= document.links.length; i-->0;)
    if (document.links[i] is one of the links you want to target)
        document.links[i].onclick= someHandlerFunction;

function someHandlerFunction() {
    alert(this);
    return false;
}

, JS ( on... addEventListener attachEvent IE) .

+7

statckoverflow

$(document).click(function(event) {
    var text = $(event.target).text();
});
+5
<a href="javascript:alert(getClickedElement('test'))" id="test">click me!!!</a>

<script>
function getClickedElement (id) {
    return document.getElementById(id);
}
</script>

or, if you cannot predict the identifier, you can use Javascript to attach events after the page loads. Take a look at jQuery. Use something like$('a').click(function() {return this.id; });

+2
source

you can pass this as a parameter, and then you can find out what kind of element you are looking for. eg:

<html>
<head>
  <script>
    function getClickedElement ($this) {

    }
  </script>
</head>enter code here
<body>
  <a href="javascript:alert(getClickedElement(this))" id="test">click me!!!</a>
</body>
</html>

hope this helps you, it helped me :)

0
source

All Articles