Reputation: 345
I am trying to loop a function a number of times but it doesn't work for some reason. anybody see the problem?
this works
<script>
$(document).ready(function() {
$('.menuitem0').hover(function(){
$('.boxitem0').addClass('box_hover');
},
function(){
$('.box_item0').removeClass('box_hover');
});
}});
</script>
but when i try and loop it it doesnt work
<script>
$(document).ready(function() {
for(var i = 0; i < 10; i++) {
$('.menuitem'+i).hover(function(){
$('.box_item'+i).addClass('box_hover');
},
function(){
$('.box_item'+i).removeClass('box_hover');
});
}});
</script>
Upvotes: 1
Views: 156
Reputation: 318302
By the time the hover callback executes, the loop has finished, and i
is always 10
You need a closure
$(document).ready(function() {
for(var i = 0; i < 10; i++) {
(function(k) {
$('.menuitem'+k).hover(function(){
$('.box_item'+k).addClass('box_hover');
},
function(){
$('.box_item'+k).removeClass('box_hover');
});
}
}});
A better approach would be to target the correct elements, and not use a loop at all, for instance with the attribute starts with selector, and assuming the box is inside the menu
$(document).ready(function() {
$('[class^="menuitem"]').hover(function(){
$('.box_item', this).addClass('box_hover');
},
function(){
$('.box_item', this).removeClass('box_hover');
});
});
Upvotes: 2