3

我正在将我的一个项目转换为使用 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();

请注意,这些名称只是通用名称,以便于输入

4

2 回答 2

2

in$(".actionBtns").on('click', '.editButton', () => {this.handlerEditBtnClick()}) handlerEditBtnClick函数在不同的上下文中被调用(this指类),
因为()=>{}相当于function(){}.bind(this)所以你可以这样做

$(".actionBtns").on('click', '.editButton', () => {this.handlerEditBtnClick()})

或者

$(".actionBtns").on('click', '.editButton', this.handlerEditBtnClick.bind(this))

然后访问被点击的按钮,您可以随时使用e.target
(或e.currentTarget根据您的需要)

function handlerEditBtnClick(e) {
 console.log(e.target); // button that was clicked
}
于 2016-01-01T12:26:50.940 回答
1

你也可以这样做(是的,在 ES5 语法中):

$('.element').click(function (){
    $(this)===$('.element') //true
});

可能是因为 jQuery 在编写“箭头方式”时无法将选择器绑定到函数(转换为 ES6 之后)。

在几个特定情况下检查了自己,或者只是使用event.target.

于 2017-05-04T13:25:34.510 回答