Sandra Schlichting Sandra Schlichting - 3 months ago 13
Javascript Question

Detect which link was clicked? Always returns undefined. What's wrong?

I am trying to detect which of the first 3 links is being clicked on by outputting the links ID.

It always returns

undefined
.

What's wrong?

<html>
<head>

<script src="http://code.jquery.com/jquery-latest.js"></script>

<script type="text/javascript">
window.onload = function() {

onclick = function() {
alert(this.id);
return false;
}
}
</script>
</head>

<body>

<a class="a" name="a" id="1" href="#">---1---</a>
<a class="a" name="a" id="2" href="#">---2---</a>
<a class="a" name="a" id="3" href="#">---3---</a>

<a href="#"> normal link </a>

</body>
</html>

Answer

You are not targeting any of the links.

  window.onload = function() {
    $("a.a").click(function() {
      alert(this.id);
      return false;
    });
  }

What this is doing ($("a.a").click(function(){) is looking for any click events on anchors of class name 'a' and run the following anonymous function.