I have following code
for (var i = 0; i < that.$el.mini.length; i++) {
var pag = that.$el.mini[i].pagination;
// Mini-Slider Pagination
$('li', pag).each( function(j, el) {
$(el).click( function() {
/*
* Toggle Mini-Slide
*/
that.slider_fn.mini.show(i, j);
return false;
});
});
}
So, basically, what I want to do is run this function that.slider_fn.mini.show(i, j); when the element is clicked.
The problem is that I want to use the variable i, which changes its value in the loop. When the element is clicked, i is valued as the latest number, that is that.$el.mini.length.
How can I make JavaScript (or a function) to memorize that particular number?
4 Answers 4
Use a closure to close over the value of i:
$(el).click( (function(i_){
return function() {
that.slider_fn.mini.show(i_, j);
return false;
};
})(i));
Beforehand, your function was referencing the variable called i, now on each iteration you create a new function that references i_, and this variable is unique to each function and references the value of i when the function was created.
1 Comment
You need to create a function closure and pass in the variables that you want to persist as arguments as follows:
for (var i = 0; i < that.$el.mini.length; i++) {
var pag = that.$el.mini[i].pagination;
$('li', pag).each(function (j, el) {
// function closure to persist i, j, and el
(function (idx, jdx, elem) {
$(elem).click(function () {
that.slider_fn.mini.show(idx, jdx);
return false;
});
} (i, j, el));
});
}
Comments
The closure answers given are the conventional way to solve your problem, but if you don't care for the self-invoking anonymous functions, you might consider using forEach():
that.$el.mini.forEach(function (element,i){
var pag = element.pagination;
// Mini-Slider Pagination
$('li', pag).each( function(j, el) {
$(el).click( function() {
/*
* Toggle Mini-Slide
*/
that.slider_fn.mini.show(i, j);
return false;
});
});
}) ;
Caveat: forEach() is not implemented in all browsers. You can see how to shim it, as described under 'Compatibility' at https://developer.mozilla.org/en/JavaScript/Reference/global_objects/array/foreach
Comments
This is assuming that pag is an element, and that you are using jquery.
for (var i = 0; i < that.$el.mini.length; i++) {
var pag = that.$el.mini[i].pagination;
// Mini-Slider Pagination
$('li', pag).each( function(j, el) {
$(el).data('page-index', i); // add data to the element being clicked
$(el).click( function() {
/*
* Toggle Mini-Slide
*/
that.slider_fn.mini.show($(this).data('page-index'), j);
return false;
});
});
}