Dynamic jQuery Selectors, variable problem -
i'm trying make list of questions hidden answers shows upon click. code hides divs, when click on anchors, last box toggled. in case, every anchor toggles 5th box, , not own.
for(var i=1; i<6; i++){ var x = i+""; $("#box"+ x).hide(); $("#feature"+x).click(function(){ $("#box"+x).toggle(400); }); } my basic html looks this, 5 pairs:
<p><a id="feature1" href="#">1. absent message</a></p> <div id="box1">stuff here 1</div> <p><a id="feature2" href="#">2. alarm setting</a></p> <div id="box2">stuff here 2</div> if wrote out functions without using loop , string concatenation, functions want them to. can point me in right direction? doing wrong string manipulation?
your problem x shared between all copies of loop, in end it's 5, , $("#box"+x) $("#box5") when it's appending @ click time. easier way classes, this:
<p><a class="feature" href="#">1. absent message</a></p> <div class="box">stuff here 1</div> then find relatively, this:
$(".box").hide(); $(".feature").click(function() { $(this).parent().next(".box").toggle(400); }); if that's not option, need provide necessary scope loop, this:
for(var i=1; i<6; i++){ (function(x) { $("#box"+ x).hide(); $("#feature"+x).click(function(){ $("#box"+x).toggle(400); }); })(i); } by doing we're passing i anonymous function, gets own copy called x, not shared variable scoped whatever function for loop in (which what's happening).
Comments
Post a Comment