A function inside a for loop with jQuery and Javascript

允我心安 提交于 2019-12-08 01:01:37

问题


i have the following code :

$(document).ready(function () {
    for (i = 1; i <= number_of_banners; i++) {
    var selector = "#link_" + i;
    $(selector).click(function () {
        alert(i);
        });
    }
});

but the alert() can't get the "i" variable from the for loop. How can I use the i variable of for loop inside the .click function ?


回答1:


you can use this code :

$(document).ready(function () {
    for (var i = 1; i <= number_of_banners; i++) {
        var selector = "#link_" + i;
        $(selector).on('click', {id: i}, function (e) {
            alert(e.data.id);
        });
    }
});

you should use on method and use click argument in it instead of using onclick method




回答2:


Using jQuery .on(event, data, handler) you can do it easily.

$(document).ready(function () {
    for (var i = 1; i <= number_of_banners; i++) {
        var selector = "#link_" + i;
        $(selector).on('click', {id: i}, function (e) {
            alert(e.data.id);
        });
    }
});

Working sample




回答3:


Might this happen be due the fact of the JavaScript hoisting JavaScript Scoping mechanism??

For instance:

  • example of wrong loop variable binding

doesn't work as JavaScript uses function scope rather than block scope as we're usually accustomed from other languages like Java and C#. In order to make it work, one has to create a new scope by explicitly creating a new anonymous function which then binds the according variable:

  • example of correct loop variable binding

I know this doesn't directly answer the question above, but might still be useful though for others stumbling over this question.




回答4:


I think you can pass it as a parameter into the anonymous function as long as the function is declared within a scope that can access i.

function (i) {
   alert(i);
}



回答5:


a quick solution would be to use the eventData and store the current i in that:

$(document).ready(function () {
    for (var i = 1; i <= number_of_banners; i++) {
        var selector = "#link_" + i;
        $(selector).bind('click', i, function (e) {
            alert(e.data);
        });
    }
});

if you are using jquery 1.7+ then use on instead of bind



来源:https://stackoverflow.com/questions/12470879/a-function-inside-a-for-loop-with-jquery-and-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!