【问题标题】:jQuery .on event handler and ES2015 arrow functionjQuery .on 事件处理程序和 ES2015 箭头函数
【发布时间】:2016-01-01 12:12:04
【问题描述】:

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

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

【问题讨论】:

  • 我猜想重写的原因是因为我希望'this'成为函数所在的类。我将用更多代码更新我的问题以说明为什么我想做这个

标签: jquery ecmascript-6 arrow-functions


【解决方案1】:

$(".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
}

【讨论】:

  • @user1560593 是的,这就是您的名字的显示方式,您应该可以在某处更改个人资料:)
【解决方案2】:

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

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

可能是因为jQuery写成“箭头方式”时无法将选择器绑定到函数(翻译成ES6后)。

检查了几个具体案例,或者只使用event.target

【讨论】:

    猜你喜欢
    • 2016-08-23
    • 2023-01-27
    • 2016-06-23
    • 2013-01-01
    • 1970-01-01
    • 2012-01-26
    • 1970-01-01
    • 1970-01-01
    • 2018-08-16
    相关资源
    最近更新 更多