0

I have problem with the following 'registerHandlers' javascript function. When I am trying to attach the onclick even, it always displaying '3'. Here how it should work;

An alert should display anchor's zero-based index within a document instead of following the link.

For example, in the document below, the alert should display "2" when Google anchor is clicked since it is the third anchor element in the document and its zero-based index is 2.

Here the script and test page in JSFiddle

function registerHandlers() {
  var as = document.getElementsByTagName('a');
  for (var i = 0; i < as.length; i++) {
    as[i].onclick = function() {
      alert(i);
      return false;
    }
  }
}
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Haseeb Sd
  • 236
  • 3
  • 9

1 Answers1

1

This should work :)

function registerHandlers() {
  var as = document.getElementsByTagName('a');
  var j = 1;
  for (var i = 0; i < as.length; i++) {
    as[i].onclick = function() {
      alert(j);
      j++;
    }
  }
}
Aslam
  • 9,204
  • 4
  • 35
  • 51