javascript - no triggering on click event -
this simple intersting issue. suppose have 2 sections of respective class .toggle0 , .toggle1, suppose want display .toggle0 , hide .toggle1 when clicking on tag .footer0, , vice-versa : want display .toggle1 , hide .toggle0 when clicking on tag .footer1. code works correctly
$('.toggle1').hide(); var i=0; $(".footer"+i+"").click(function(){ $(".toggle"+(i+1) %2+"").hide(); $(".toggle"+i+"").show(); }); var j=1; $(".footer"+j+"").click(function(){ $(".toggle"+(j+1) %2+"").hide(); $(".toggle"+j+"").show(); }); but doesn't work in sense nothing happens on click event
for(var i=0;i<2;i++){ $(".footer"+i+"").click(function(){ $(".toggle"+(i+1) %2+"").hide(); $(".toggle"+i+"").show(); }); } if put this
$('.toggle1').hide(); var i=0; $(".footer"+i+"").click(function(){ $(".toggle"+(i+1) %2+"").hide(); $(".toggle"+i+"").show(); }); =1; $(".footer"+i+"").click(function(){ $(".toggle"+(i+1) %2+"").hide(); $(".toggle"+i+"").show(); }); .toggle1 displays , .toggle0 hides when clicking on tag .footer1 .toggle0 not display , .toggle1 not hide when clicking on tag .footer0 . seems second click event takes precedence upon first
the i within the click handler isn't evaluated until click, @ point value has changed when handler bound. if want go route, need create closure. here's 1 method so:
for (var = 0; < 2; i++) { $(".footer" + + "").click(function () { var idx = i; return function () { $(".toggle"+(idx+1) %2+"").hide(); $(".toggle"+idx+"").show(); console.log(idx); } }()); }
Comments
Post a Comment