Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. How can I use the i variable of for loop inside the .click function ?

like image 467
Kozet Avatar asked Dec 02 '25 06:12

Kozet


1 Answers

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

like image 105
Mehran Abbasi Avatar answered Dec 03 '25 18:12

Mehran Abbasi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!