0

Need to write function to alert index of clicked link in the document. For example:

 [html]
 <body>
    Links:<br/>
    <a href="//www.yahoo.com">Yahoo!</a><br/>
    <a href="//www.facebook.com">Facebook</a><br/>
    <a href="//www.google.com">Google</a><br/>
  </body>  
 [/html]

My function:

var as = document.getElementsByTagName('a');
  for (i = as.length; i>= 0; i--) {
    as[i].onclick = function() {
      alert(i);
    }
  }

Please help me fix bugs

  • I think I misunderstood your question. You are not looking to alert any contents from the link, but the actual position compared to other links yes? Like facebook would avert 1, yahoo would alert 0? Yes? – kemicofa ghost Mar 15 '15 at 12:14
  • possible duplicate of [JavaScript closure inside loops – simple practical example](http://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example) – Artjom B. Mar 15 '15 at 19:26

2 Answers2

2

The actual event occurs sometime in the future after your for loop has already finished running and thus its index is at the last value. You need to create some sort of closure that preserves the value of i uniquely for each event handler so they each have access to their own value. There are several different ways to do that, but all involve passing the i value to a function for each event handler.

Demo@fiddle

var as = document.getElementsByTagName('a');

for (var i=0, j=as.length; i<j; i++) {
    var link = as[i];
    (function(i){
        link.onclick = function() {
            alert (i);
        }
    }(i));
}
lshettyl
  • 8,166
  • 4
  • 25
  • 31
0

Since you linked jquery: DEMO

$('a').each(function(a, b){
    $(this).attr('id', a).on('click', function(e){
        e.preventDefault();
        alert($(this).attr('id'));
    });
});

If you don't want to use the id to stock the index then you can create a data-index:

DEMO 2

$('a').each(function(a, b){
    $(this).attr('data-index', a).on('click', function(e){
        e.preventDefault();
        alert($(this).attr('data-index'));
    });
});
kemicofa ghost
  • 16,349
  • 8
  • 82
  • 131