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

I'm using only javascript, not jQuery or no other javascript frameworks.I have created one anchor

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 ?

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 ?

Share Improve this question asked Aug 20, 2012 at 15:08 SmitSmit 1,56917 silver badges38 bronze badges 3
  • 2 Show us the entire loop. You simply need a closure. – Some Guy Commented Aug 20, 2012 at 15:09
  • 1 possible duplicate of Javascript function is using the last known parameters in loop?, Javascript - Dynamically assign onclick event in the loop and many more – Rob W Commented Aug 20, 2012 at 15:11
  • scroll down to "Looping with a closure" here – jbabey Commented Aug 20, 2012 at 15:13
Add a ment  | 

3 Answers 3

Reset to default 1

try following:

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

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.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745441751a4627861.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信