Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery can't get my head around this

The alert(i) onclick bind line is run on 3 divs, but all of them when clicked alert the last set value of i. I hope what I'm trying to do makes sense, it's hard to explain. Instead of alerting 1,2 or 3, it alerts 3,3,3.

// Updates bar preview box
this.updatePropertyMarkerBox = function(self, BarsID) {

    ... snip ...

    // Loop  and add event handler
    for (var i = 0; i < self.bars[BarsIndex].markers.length; i++) {

        // Add click event
        $("#bmi-" + self.containerId + "-" + i).bind('click', function() {
            alert(i);
        });
    }
like image 866
Tom Gullen Avatar asked Dec 03 '25 22:12

Tom Gullen


1 Answers

When you're iterating in the for loop, you're essentially given the address to i, if you use it within the for loop at that very moment, it will be the value expected, however if you use it later (such as in a click event) it will point to the final incremented value of 3. To get the desired affect you can create an anonymous function, like so

for (var i = 0; i < self.bars[BarsIndex].markers.length; i++) (function(i) {

    // Add click event
    $("#bmi-" + self.containerId + "-" + i).bind('click', function() {
        alert(i);
    });
})(i)
like image 116
Robert Avatar answered Dec 06 '25 11:12

Robert



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!