Calling onclick with local variable

耗尽温柔 提交于 2019-12-24 13:17:12

问题


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).


回答1:


If you can reverse the order that the arguments are received, you should be able to do this...

a.onclick = goog.bind(this.doSomething, this, i);

So your doSomething should look like this...

namespace.Clazz.prototype.doSomething = function(index, event) {
  console.log('index: ' + index);
};

At least that's how it looks from the Google Closure Library source.




回答2:


a.onclick = (function(i) { return function() {goog.bind.....}; })(i);

That creates a new closure in which the value of i is fixed.




回答3:


Something like this may work better for you:

a.onclick = function() {
    doSomething(this, i)
}


来源:https://stackoverflow.com/questions/8919743/calling-onclick-with-local-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!