I’m trying to make a while-loop in my Javascript.
So far, I’ve got this:
<script>
$(document).ready(function(){
var i=0;
while (i<9999) {
$(".add_new_item_field" + i).hide();
$(".add_new_item_button" + i).click(function(){
$(".add_new_item_field" + i).slideToggle("slow");
});
i++;
}
});
</script>
Goal is to make this work:
<div class="add_new_item_button1"></div>
<div class="add_new_item_button2"></div>
<div class="add_new_item_button3"></div>
...
<div class="add_new_item_field1">Show me something</div>
<div class="add_new_item_field2">Show me something</div>
<div class="add_new_item_field3">Show me something</div>
...
But for some reason, it’s not working. Am I missing something here?
Your problem is that the concatenation in the line
$(".add_new_item_field" + i).slideToggle("slow");happens when you click one of the divs. Yet, the loop that had set up the handlers was run long ago then andialready has a value of9999. Use a closure as @David demonstrated to avoid this.However, I feel this is the wrong approach. Setting up 10000 click handlers, and executing 20000 jQuery selection does make your page very, very slow. Use one common class for the button, and one common class for the fields. If you can’t depend on a certain document order, give them unique ids to refer to each other – but not classes.
Then hide all the fields with one single line of CSS, and use event delegation for the buttons to fire 1 single function that looks up the field by id from the data attached to the clicked button.