最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin1浏览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 ?

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.

发布评论

评论列表(0)

  1. 暂无评论