0

I'm using only javascript, not jQuery or no other javascript frameworks.

I have created one anchor tag like:

var _a = document.createElement('a');

now I want to add onclick for this tag. I have tried following:

_a.onclick = function(){ mycode(id); }

The function applies on that but the anchor tags are create in loop... so mycode(id) is always taking the last value of the loop.

Can any one help me out in this ?

Smit
  • 1,559
  • 17
  • 38
  • 2
    Show us the entire loop. You simply need a closure. – Some Guy Aug 20 '12 at 15:09
  • 1
    possible duplicate of [Javascript function is using the last known parameters in loop?](http://stackoverflow.com/questions/9439700/javascript-function-is-using-the-last-known-parameters-in-loop), [Javascript - Dynamically assign onclick event in the loop](http://stackoverflow.com/questions/5040069/javascript-dynamically-assign-onclick-event-in-the-loop) and many more – Rob W Aug 20 '12 at 15:11
  • scroll down to "Looping with a closure" [here](http://enterprisejquery.com/2010/10/how-good-c-habits-can-encourage-bad-javascript-habits-part-3/) – jbabey Aug 20 '12 at 15:13

3 Answers3

1

try following:

_a.onclick = (function(id){return function(){ mycode(id); }})(id);
Smit
  • 1,559
  • 17
  • 38
1

Probably you need a function to create your handler like this:

function createHandler( id ) {
  return function(){ mycode( id ); };
}

and then assign inside the loop

for ( i= ... ) {
   _a.onclick = createHandler( i );
}

On the other hand you maybe should use addEventListener() (MDN docu) to add events to elements:

_a.addEventListener( 'click', createHandler( i ) );
Sirko
  • 72,589
  • 19
  • 149
  • 183
1
for(var id = 0; id < 10; id++){
    var _a = document.createElement('a');
    _a.onclick = (function(id){
        return function (){
            mycode(id);
        }
    })(id);
}

That should fix it.

Some Guy
  • 15,854
  • 10
  • 58
  • 67