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
3 Answers
Reset to default 1try 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条)