如何存储局部变量在jQuery点击函数? [英] How to store local variables in jQuery click functions?

查看:135
本文介绍了如何存储局部变量在jQuery点击函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想弄清楚如何在jQuery的click()事件中创建的函数中存储外部变量值。

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>

因此,发生的事情是正确附加的,但'gid'的值总是最后递增的值'i'。我不知道如何在这种情况下设置私有变量。

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.

推荐答案

可以创建一个闭包, $ c> i 到闭包的局部变量。然后,在创建闭包的时候, gid 变量将被分配 i 的值,

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

这篇关于如何存储局部变量在jQuery点击函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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