我正在将我的一个项目转换为使用 ES2015,但是当涉及到 jQuery 的 .on 事件处理程序时,我遇到了一个问题,自然与 'this' 关键字有关。
这是我的示例代码:
$(".actionBtns").on('click', '.editButton', this.handlerEditBtnClick) //Would give 'this' the value of the button clicked
$(".actionBtns").on('click', '.editButton', () => {this.handlerEditBtnClick()}) //Would give 'this' the value of the class
我不确定我应该如何重写上面代码中的第一行以使用 ES2015。
在函数 handlerEditBtnClick 中,我需要“this”作为类,但我还希望访问被单击的按钮。
我的尝试(上面代码中的第二行)没有让我访问被单击的按钮 DOM 元素——至少我无法想到访问它。
谢谢,
卢克
编辑 这是 handlerEditBtnClick() 函数:
handlerEditBtnClicked() {
var $item = $(this); //This isn't re-written yet, so 'this' actually refers to the edit button that was clicked
this.editItem($item); //This is where I need 'this' to be the class
}
你可以看到我需要'this'是两个不同的东西。我不完全确定如何从 handlerEditBtnClick 中调用 editItem 函数,而不是 this.editItem();
请注意,这些名称只是通用名称,以便于输入