sorry for my bad english.
I’ve got such a question: why the first code:
<html>
<head>
<style>
body { position: relative; }
table { position: absolute; top: 200px; left: 200px; }
div { width: 100px; height: 100px; background-color: black; margin: auto auto; }
</style>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
$(document).ready(function(){
for(i = 0; i < 100; i++) {
var j = i + '';
$("#menu_div_" + j).mouseover(function(){
$("#menu_div_" + j).clearQueue();
$("#menu_div_" + j).stop();
$("#menu_div_" + j).animate({
width: 150,
height: 150
}, 600
);
});
$("#menu_div_" + j).mouseout(function(){
$("#menu_div_" + j).clearQueue();
$("#menu_div_" + j).stop();
$("#menu_div_" + j).animate({
width: 100,
height: 100
}, 600
);
});
}
});
</script>
</head>
<body>
<table id="menu">
<? for($i = 0; $i < 10; $i++) { ?>
<tr>
<? for($j = 0; $j < 10; $j++) { ?>
<td>
<div id="menu_div_<? echo ($i * 10) + $j; ?>">
</div>
</td>
<? } ?>
</tr>
<? } ?>
</table>
</body>
</html>
doesn’t work exactly the same like in this code (“for” loop is written in php):
<html>
<head>
<style>
body { position: relative; }
table { position: absolute; top: 200px; left: 200px; }
div { width: 100px; height: 100px; background-color: black; margin: auto auto; }
</style>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
$(document).ready(function(){
<?php for($i = 0; $i < 100; $i++) { ?>
$("#menu_div_" + <?php echo $i; ?>).mouseover(function(){
$("#menu_div_" + <?php echo $i; ?>).clearQueue();
$("#menu_div_" + <?php echo $i; ?>).stop();
$("#menu_div_" + <?php echo $i; ?>).animate({
width: 150,
height: 150
}, 600
);
});
$("#menu_div_" + <?php echo $i; ?>).mouseout(function(){
$("#menu_div_" + <?php echo $i; ?>).clearQueue();
$("#menu_div_" + <?php echo $i; ?>).stop();
$("#menu_div_" + <?php echo $i; ?>).animate({
width: 100,
height: 100
}, 600
);
});
<?php } ?>
});
</script>
</head>
<body>
<table id="menu">
<? for($i = 0; $i < 10; $i++) { ?>
<tr>
<? for($j = 0; $j < 10; $j++) { ?>
<td>
<div id="menu_div_<? echo ($i * 10) + $j; ?>">
</div>
</td>
<? } ?>
</tr>
<? } ?>
</table>
</body>
</html>
Quick explanation:
In the first one, “events” from all “div” tags result in changing the size of the last element (I don’t know why). In the second – “event” from each “div” results in changing size of the same “div” (what, in my opinion, should also happen in the first code too).
How can I correct first code to make it work like the second one?
jdoesn’t equal what you think it will. It will ALWAYS come back with 99. This is due to the defining anonymous functions within a loop.Luckily, with a little jQuery magic, this is easily fixed. Rather than trying to reference each element directly,
$('#menu_div_'+j), just use$(this). Inside jQuery event handlers,thisis automatically set the to element/target of the event.JSFiddle Demo