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

发布于 2024-10-05 11:04:02 字数 384 浏览 0 评论 0原文

我有这个小脚本:

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。

有没有办法知道哪个类添加了事件?

I have this little script:

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

And I want to know "this" in the popup function, but if I try something like alert(this.el.id) it says there is no this.el.

Is there a way to know which class adds the event?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

反话 2024-10-12 11:04:02

更改附加事件,以便被调用者拥有正确的上下文。否则,事件侦听器的上下文将是目标元素。

// Change this line
this.el.addEvent('click', this.popup);
//To this
this.el.addEvent('click', this.popup.bind(this)); // popup->this == this

jsfiddle 在这里
请参阅 mootools 文档。绑定函数的上下文。

Change the attach event so the callee has the proper context. Otherwise the context of an event listener will be the target element.

// Change this line
this.el.addEvent('click', this.popup);
//To this
this.el.addEvent('click', this.popup.bind(this)); // popup->this == this

jsfiddle here
See mootools documentation. Binding the context of a function.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文