jQuery Closures, Loops and Events

前端 未结 3 510
春和景丽
春和景丽 2020-12-16 20:43

I have a question similar to the one here: Event handlers inside a Javascript loop - need a closure? but I\'m using jQuery and the solution given seems to fire the event whe

3条回答
  •  旧巷少年郎
    2020-12-16 21:00

    Solution by Greg is still valid, but you can do it without creating additional closure now, by utilizing eventData parameter of jQuery click method (or bind or any other event-binding method, for that matter).

    .click({indGroup: i, indValue : j}, function(event) {
        alert(event.data.indGroup);
        alert(event.data.indValue);
        ...
    });
    

    Looks much simpler and probably more efficient (one less closure per iteration).

    Documentation for bind method has description and some examples on event data.

提交回复
热议问题