How to loop in jQuery -
i have couple of jquery function similar syntax.
$("#item-1").hover(function(){ $(".item-1").animate({opacity:1},"slow"); },function(){ $(".item-1").animate({opacity:0},"slow"); }); $("#item-2").hover(function(){ $(".item-2").animate({opacity:1},"slow"); },function(){ $(".item-2").animate({opacity:0},"slow"); }); $("#item-3").hover(function(){ $(".item-3").animate({opacity:1},"slow"); },function(){ $(".item-3").animate({opacity:0},"slow"); });
my question how shorten code of loop. tried following didn’t work:
for (i = 1; <= 3; ++i) { $("#item-" + i).hover(function(){ $(".item-" + i).animate({opacity:1},"slow"); },function(){ $(".item-" + i).animate({opacity:0},"slow"); }); }
this should work :
for (i = 1; <= 3; ++i) { (function(index){ $("#item-" + index).hover(function(){ $(".item-" + index).animate({opacity:1},"slow"); },function(){ $(".item-" + index).animate({opacity:0},"slow"); }); })(i); }
the problem loop variable not captured hover function. this, variable captured properly.
Comments
Post a Comment