On Jul 25, 7:22 am, Henry <[EMAIL PROTECTED]> wrote:
> for (var i = 1; i < totalPages + 1; i++) {
> $("#pages_panel").append($("<span> " + i + "</span>")
> .click(
> (function(x){
> return (function(){
> pageClicked(x);
> console.log("i:" + x);
> });
> })(i)
> )
> );
> }
Another approach is to use the new Function() constructor which is
evaluated in the global scope and nice for very short functions:
for (var i = 1; i < totalPages + 1; i++) {
$("#pages_panel").append($("<span> " + i + "</span>")
.click( new Function("pageClicked("+i+"); console.log('i:"+i
+"'); ));
}
If you are going to use Henry's approach (which is very much correct)
I usually prefer to pull it out into another function to avoid so many
nested anonymous functions. I think it's easier to read:
function getClickFunc(i) {
return (function() {
pageClicked(i);
console.log("i:"+i);
});
}
for (var i = 1; i < totalPages + 1; i++) {
$("#pages_panel").append($("<span> " + i + "</span>")
.click( getClickFunc(i) );
}
(careful, above not tested and is highly subject to typos. But the
concept should be clear)
Matt Kruse