我有这段代码:
this.json.each(function(obj, index) {
var li = new Element('li');
var a = new Element('a', {
'href': '#',
'rel': obj.id,
events: {
'click': function(e) {
this.doSteps(this.step + 1); // <-- causing issue
}
}
});
var img = new Element('img', {
'src': imgd + obj.img,
'alt': obj.name
});
img.inject(a);
a.inject(li);
li.inject(ul);
});
我在控制台中收到“this.doSteps 不是函数”的错误。有人可以帮我解决这个问题并解释一下解决方案吗?
提前致谢。
最佳答案
您需要绑定(bind)this
,因此函数的作用域引用了正确的this
。
'click': function(e) {
this.doSteps(this.step + 1);
}.bind(this)
这是 MooTools 的方式。
关于javascript - 如何在 JavaScript 中使用 "this",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7993472/