使用jQuery和Javascript在for循环中的函数 [英] A function inside a for loop with jQuery and Javascript

查看:98
本文介绍了使用jQuery和Javascript在for循环中的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

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

但alert()无法从for循环中获取i变量。
如何在.click函数中使用for循环的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 ?

推荐答案

你可以使用这段代码:

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

你应该在上使用方法并使用点击其中的参数而不是使用 onclick 方法

这篇关于使用jQuery和Javascript在for循环中的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆