Thursday, January 7, 2010

Javascript Closure to remember variable in context

Closure can be used to remember variable in the context. e.g.
<script>
$().ready(function() {
var ts = $('.t');
for(var i = 0; i < ts.length; i++) {
var onClick = function(i) {
return function() {
alert(i);
return false;
}
}
$(ts.get(i)).bind('click', onClick(i));
}
});
</script>
<body>
<p><a class='t' href=''>Google</a></p>
<p><a class='t' href=''>Yahoo</a></p>
</body>

No comments:

Post a Comment