使用局部变量调用 onclick
首先,我很抱歉问了一些必须在此处回答的问题(我一直在寻找!)
我想这样做:
var i;
for (i = 0; i < 5; i++) {
...
// Add an anchor to the dom
...
a.onclick = goog.bind(this.doSomething, this);
...
}
namespace.Clazz.prototype.doSomething = function(event, index) {
console.log('index: ' + index);
}
我想要 5 个锚点,每个锚点将 i
的不同值传递给 doSomething
单击时(以及单击事件)。我还想将 this
的上下文保留在 doSomething
中(因此是绑定)。
First, apologies for asking something that must be answered here somewhere (I've been looking!)
I want to do this:
var i;
for (i = 0; i < 5; i++) {
...
// Add an anchor to the dom
...
a.onclick = goog.bind(this.doSomething, this);
...
}
namespace.Clazz.prototype.doSomething = function(event, index) {
console.log('index: ' + index);
}
I want 5 anchors the each pass a different value for i
to doSomething
when clicked (along with the click event). I also want to keep the context of this
in doSomething
(hence the bind).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您可以颠倒接收参数的顺序,您应该能够执行此操作...
因此您的
doSomething
应该如下所示...至少从 Google Closure 库源代码。
If you can reverse the order that the arguments are received, you should be able to do this...
So your
doSomething
should look like this...At least that's how it looks from the Google Closure Library source.
这会创建一个新的闭包,其中 i 的值是固定的。
That creates a new closure in which the value of i is fixed.
像这样的东西可能更适合你:
Something like this may work better for you: