我希望标题有意义。
我正在使用for
循环创建一个或多个$(document).on()
元素。每个里面$(document).on()
元素已创建,我需要它来调用函数 foo(currentIndex)
其中currentIndex
是 .on()
时索引的值定义。
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>
问题:当我使用.on()
单击元素时我创建的函数,它使用 i
的最新值(在本例中为 2)。
期望的行为:当我点击 div1 时,它应该发出警报 0
,当我单击 div2 时,它应该发出警报 1
(.on()
定义时的当前索引。)
最佳答案
您可以使用.data()
来存储索引值
$(element[i]).data('index', i);
$(document).on(event[i], element[i], function () {
foo($(this).data('index'));
});
关于javascript - 在 for 循环中创建 .on() 元素时,如何使 .on(function) 调用当前索引?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30898440/