0

I hope the title makes sense.

I am using a for loop to create one or more $(document).on() elements. Inside each $(document).on() element created, I need it to call a function foo(currentIndex) where the currentIndex is the value of the index at the time of the .on() definition.

Fiddle: https://jsfiddle.net/xLbses7w/

JavaScript/jQuery:

var event = ['click', 'click'];
var element = ['#someId', '#someId2'];

for (i = 0; i < event.length; i++)
{
    $(document).on(event[i], element[i], function ()
    {
        foo(i);    // would like this to be the value of i when the function was created
    });
}


function foo(arg)
{
    alert(arg);
}

HTML:

<div id="someId">div1</div> <br/>
<div id="someId2">div2</div>

The problem: When I click on the element using the .on() function I have created, it uses the latest value of i (which in this case is 2).

Desired Behavior: When I click on div1, it should alert 0, and when I click on div2 it should alert 1 (the current indexes at the time of .on() definition.)

AlbatrossCafe
  • 1,710
  • 6
  • 26
  • 49
  • Relevant: http://stackoverflow.com/questions/9069614/javascript-puzzle-scope/9069680#9069680 – canon Jun 17 '15 at 17:34

2 Answers2

2

You can use .data() to store the index value

$(element[i]).data('index', i);
$(document).on(event[i], element[i], function () {
    foo($(this).data('index')); 
});

DEMO

Satpal
  • 132,252
  • 13
  • 159
  • 168
1

You can create a closure:

for (i = 0; i < event.length; i++) {
    (function (i) {
        $(document).on(event[i], element[i], function () {
            foo(i); // would like this to be the value of i when the function was created
        });
    })(i);
}

-DEMO-

A. Wolff
  • 74,033
  • 9
  • 94
  • 155