Javascript variable value as number in html class name -


i want put variable 'i' in code:

do { $('.dot:nth-child(1)').click(function(){   $('.inside').animate({     'width' : (i*width)+'%'   }, 500); });     i++; } while (i <= number); 

like - don't work:

do { $('.dot:nth-child('+ +')').click(function(){   $('.inside').animate({     'width' : (i*width)+'%'   }, 500); });     i++; } while (i <= number); 

this classic closure issue: function pass click has enduring reference i variable, not copy of of when function created. of clicks end using value of i when click occurs (after loop finishes).

the usual solution use builder function:

do {   $('.dot:nth-child('+ +')').click(buildhandler(i));       i++; } while (i <= number);  function buildhandler(index) {   return function(){     $('.inside').animate({       'width' : (index*width)+'%'     }, 500);   }; } 

that said, in case, don't need different handler functions each element; instead, have one handler function checks see child it's dealing with:

$('.dot').click(function(){   var index = $(this).index();   $('.inside').animate({     'width' : (index*width)+'%'   }, 500); }); 

more: index


Comments

Popular posts from this blog

cakephp - simple blog with croogo -

How to group boxplot outliers in gnuplot -

bash - Performing variable substitution in a string -