在 for 循环中创建 .on() 元素时,如何使 .on(函数) 调用当前索引

When creating .on() elements in a for loop, how can I make the .on(function) call the current index?

本文关键字:on 函数 何使 调用 索引 元素 循环 for 创建      更新时间:2023-09-26

我希望这个标题有意义。

我正在使用for循环来创建一个或多个$(document).on()元素。在每个创建的$(document).on()元素中,我需要它来调用一个函数foo(currentIndex)其中currentIndex.on()定义时的索引值。

小提琴: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')); 
});

演示

您可以创建闭包:

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);
}

-演示-