Javascript Mootools 点击事件和他的调用者?

标签 javascript dom-events mootools javascript-framework

我有这个小脚本:

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/

相关文章:

asp.net - 从子页面刷新父页面

Javascript 适用于除 IE 9 以外的所有浏览器

javascript - 如何在 JavaScript 中跟踪回调函数事件?

javascript - 在请求之前评估数据变量

javascript - 正则表达式 - 查找不在 ","之后的所有换行符

javascript - 在 knockout 中将属性绑定(bind)到模型 View 函数

javascript - 显示加载图像

javascript - 如何使用 onsubmit 表单 asp.net mvc 模型中的数据更新 Javascript 中的 div 标签

JavaScript:MooTools - 使用类获取字符串,使用父函数返回它

google-chrome - Chrome 无法释放内存,垃圾回收没有按预期进行(Mootools/MochaUI 库)