将其他参数传递给事件处理程序

编程入门 行业动态 更新时间:2024-10-28 00:22:48
本文介绍了将其他参数传递给事件处理程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我在这样的对象中定义了我的函数:

i have my functions defined in an object like this:

_clickHandler: function(event){ event.preventDefault(); }, attachClickEv: function(element){ ...... element.on('click', this._clickHandler); },

问题是我似乎无法将this传递给clickHandler函数

the problem is that I cannot seem to pass "this" to the clickHandler function

我知道我可以将其包装在另一个函数中,例如

I know that I could wrap that in another function like

var tthis = this; element.on('click', function(event){ tthis._clickHandler(event, tthis); });

但后来我不能用

element.off('click', this._clickHandler);

还有其他办法吗?

推荐答案

您可以使用bind。这是一个例子:

You can use bind for that. Here is an example:

element.on('click', this._clickHandler.bind(this)); //later in the code... _clickHandler: function(event) { }

既然你正在使用jQuery,你也可以使用 jQuery.proxy()太。更多信息: api.jquery/jQuery.proxy

Since you're using jQuery though, you can also use jQuery.proxy() too. More here: api.jquery/jQuery.proxy

更新:

要访问回调中的元素,您必须使用 event.target 或 event.currentTarget 或执行以下操作(取决于您正在做什么 ):

To get access to the element inside the callback you would have to use event.target or event.currentTarget or do the following (depends on what you're doing):

element.on('click', this._clickHandler.bind(this, element)); //later in the code... _clickHandler: function(element, event) { }

另一种方法是将元素设置为对象的属性,如: this.element = $(' #el')然后在你的回调中使用它。

Another way is to set the element as a property of the object like: this.element = $('#el') and then use that in your callback(s).

实例: jsbin/mezuberucu/1/edit?html,js,output

更多推荐

将其他参数传递给事件处理程序

本文发布于:2023-11-23 10:41:49,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1621148.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:参数   事件   程序

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!