Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to store local variables in jQuery click functions?

I'm trying to figure out how to store external variable values in the functions created during jQuery's click() event. Here's a sample of the code I'm working with now.

for(var i=0; i<3; i++){
    $('#tmpid'+i).click(function(){
        var gid = i;
        alert(gid);
    });
}

<div id="tmpid0">1al</div>
<div id="tmpid1">asd</div>
<div id="tmpid2">qwe</div>

So what's happening is that the events are attaching properly, but the value of 'gid' is always the last incremented value of 'i'. I'm not sure how to setup the private variable in this situation.

like image 273
Geuis Avatar asked Sep 28 '09 07:09

Geuis


1 Answers

You can create a closure and assign i to a local variable of the closure. The gid variable will then be assigned the value of i at the point that the closure was created rather than when the function is run.

for(var i=0; i<3; i++){
    (function() {
        var gid = i;
        $('#tmpid'+i).click(function(){
            alert(gid);
        });
    })();
}
like image 85
Rich Seller Avatar answered Sep 18 '22 00:09

Rich Seller