How to store local variables in jQuery click funct

2019-02-03 11:11发布

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.

5条回答
男人必须洒脱
2楼-- · 2019-02-03 11:42

I read back up on jQuery's native data() method. I implemented this and it works as well. Its hiding some of the actual functionality of how the closures are being handled, but its simple and pretty clean to implement.

查看更多
Anthone
3楼-- · 2019-02-03 11:45

Alternatively, the first argument of click (or bind) for jQuery is an object that gets attached to the event as data.

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

I find this a little more readable than the closure solution, but it comes down to taste.

查看更多
小情绪 Triste *
4楼-- · 2019-02-03 11:47
for(var i=0; i<3; i++){
    $('#tmpid'+i).click((function(gid){
        return function(){
             alert(gid);
        }
    })(i));
}

there are many ways to do it, this one works and looks easy.

edit

another way:

for(var i=0; i<3; i++){
    $('#tmpid'+i).click([i],function(e){
        alert(e.data[0]);
    });
查看更多
干净又极端
5楼-- · 2019-02-03 11:48

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);
        });
    })();
}
查看更多
Lonely孤独者°
6楼-- · 2019-02-03 11:49

You've created a closure, where the variable "i" is shared between multiple click handlers.

Since Javascript doesn't have block scope, you'll need to pass "i" to a new function so it is copied-by-value to a new instance:

function bindStuff(i) {
    $('#tmpid'+i).click(function(e){
                    var gid = i;
                    alert(gid);
            });
}

for(var i=0; i<3; i++){ bindStuff(i); }

Here's another similar question: JavaScript closure inside loops – simple practical example

查看更多
登录 后发表回答