箭头函数 VS jQuery 中带有 $(this) 的匿名函数

问题描述 投票:0回答:1

我在编码过程中发现了这个错误(或功能):

如果您使用箭头函数作为 jQuery 事件的处理程序,则构造 $(this) 在此函数内不起作用。

我知道箭头和匿名函数是不同的,在某些情况下它们是不可互换的,但如何解释这种确切的情况?

这里是代码示例https://codepen.io/wd3/pen/abxjyQG您可以看到两个带有箭头和匿名函数的相似块

$(document).ready(()=>{
  // input1 - anonymous
  $('.input1').on('click', function(){
    $(this).removeClass('wrong')
    $('.input1').val(parseInt($('.input1').val()) + 1)
  })
  
  // input2 - arrow
  $('.input2').on('click', ()=>{
    $(this).removeClass('wrong')
    $('.input2').val(parseInt($('.input2').val()) + 1)
  })
  
  // input3 - arrow with currentTarget
  $('.input3').on('click', (e)=>{
    $(e.currentTarget).removeClass('wrong')
    $('.input3').val(parseInt($('.input3').val()) + 1)
  })
  
})
javascript jquery this anonymous-function arrow-functions
1个回答
0
投票

在撰写本文时发现了更多信息。 所以如果你在 jQuery 中使用箭头函数,你应该使用 event.currentTarget 而不是 this

示例:

$('.input3').on('click', (event)=>{
    $(event.currentTarget).removeClass('wrong')
  })
© www.soinside.com 2019 - 2024. All rights reserved.