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.)