我有这个小脚本:
var moolang = new Class({
initialize: function(element) {
this.el = $(element);
this.el.addEvent('click', this.popup);
},
popup: function()
{
//this.id = the id of the element.
}
});
我想知道弹出函数中的“this”,但如果我尝试类似 alert(this.el.id)
的内容,它会说没有 this.el。
有没有办法知道哪个类添加了事件?
最佳答案
更改附加事件,以便被调用者拥有正确的上下文。否则,事件监听器的上下文将是目标元素。
// Change this line
this.el.addEvent('click', this.popup);
//To this
this.el.addEvent('click', this.popup.bind(this)); // popup->this == this
jsfiddle here 请参阅 mootools documentation 。绑定(bind)函数的上下文。
关于Javascript Mootools 点击事件和他的调用者?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4328935/