-->

Calling onclick with local variable

2019-08-15 03:05发布

问题:

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