简体   繁体   中英

how to add onclick event on anchor tag that is generated with javascript?

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 ?

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 ) );
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.

尝试以下操作:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM