简体   繁体   English

使用jQuery和Javascript在for循环中的函数

[英]A function inside a for loop with jQuery and Javascript

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. 但是alert()无法从for循环中获取“i”变量。 How can I use the i variable of for loop inside the .click function ? 如何在.click函数中使用for循环的i变量?

Using jQuery .on(event, data, handler) you can do it easily. 使用jQuery .on(事件,数据,处理程序),您可以轻松完成。

$(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 工作样本

Might this happen be due the fact of the JavaScript hoisting JavaScript Scoping mechanism?? 这可能是由于JavaScript提升 JavaScript Scoping机制的事实?

For instance: 例如:

doesn't work as JavaScript uses function scope rather than block scope as we're usually accustomed from other languages like Java and C#. 因为我们通常习惯于Java和C#等其他语言,因此JavaScript不能使用函数作用域而不是块作用域 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: 为了使它工作,必须通过显式创建一个新的匿名函数来创建一个新的范围,然后绑定相应的变量:

I know this doesn't directly answer the question above, but might still be useful though for others stumbling over this question. 我知道这并没有直接回答上面的问题,但可能仍然有用,但对于其他人来说,这个问题磕磕绊绊。

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 你应该使用on方法并在其中使用click参数而不是使用onclick方法

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. 我认为你可以将它作为参数传递给匿名函数,只要该函数在可以访问i的范围内声明即可。

function (i) {
   alert(i);
}

a quick solution would be to use the eventData and store the current i in that: 一个快速的解决方案是使用eventData并将当前的i存储在:

$(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 如果你使用jquery 1.7+然后使用on而不是bind

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM