如何在 jQuery 点击函数中存储局部变量?
我试图弄清楚如何在 jQuery 的 click() 事件期间创建的函数中存储外部变量值。这是我现在正在使用的代码示例。
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”的最后一个递增值。我不确定在这种情况下如何设置私有变量。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您可以创建一个闭包并将
i
分配给该闭包的局部变量。然后,在创建闭包时而不是在函数运行时,为gid
变量分配i
的值。You can create a closure and assign
i
to a local variable of the closure. Thegid
variable will then be assigned the value ofi
at the point that the closure was created rather than when the function is run.有很多方法可以做到这一点,这个方法很有效而且看起来很简单。
另一种方式编辑
:
there are many ways to do it, this one works and looks easy.
edit
another way:
您已经创建了一个闭包,其中变量“i”在多个单击处理程序之间共享。
由于 Javascript 没有块作用域,因此您需要将“i”传递给新函数,以便将其按值复制到新实例:
这是另一个类似的问题:
循环内的 JavaScript 闭包 - 简单的实际示例
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:
Here's another similar question:
JavaScript closure inside loops – simple practical example
或者,jQuery 的单击(或绑定)的第一个参数是一个作为数据附加到事件的对象。
我发现这比闭包解决方案更具可读性,但这取决于品味。
Alternatively, the first argument of click (or bind) for jQuery is an object that gets attached to the event as data.
I find this a little more readable than the closure solution, but it comes down to taste.
我重新阅读了 jQuery 的本机 data() 方法。我实现了这个并且它也有效。它隐藏了如何处理闭包的一些实际功能,但其实现起来简单且非常干净。
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.