Dynamic jQuery Selectors, variable problem
I'm just trying to make a list of questions with hidden answers that shows upon click. My code hides all divs, but when I click on the anchors, only the last box is toggled. In this case, every anchor toggles the 5th box, and not their 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 like this, but with 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 I wrote out the functions without using the for loop and string concatenation, the functions do what I want them to. Can someone point me in the right direction? Am I doing something wrong with the string manipulation?
Your problem is that x
is shared between all copies of the loop, so in the end it's always 5
, and $("#box"+x)
will always be $("#box5")
when it's appending at click time. An easier way would be classes, like this:
<p><a class="feature" href="#">1. Absent Message</a></p>
<div class="box">Stuff here 1</div>
Then find it relatively, like this:
$(".box").hide();
$(".feature").click(function() {
$(this).parent().next(".box").toggle(400);
});
If that's not an option, you need to provide the necessary scope to your loop, like this:
for(var i=1; i<6; i++){
(function(x) {
$("#box"+ x).hide();
$("#feature"+x).click(function(){
$("#box"+x).toggle(400);
});
})(i);
}
By doing this we're passing i
into the anonymous function, which gets its own copy called x
, not a shared variable scoped to whatever function your for
loop is in (which is what's currently happening).
精彩评论