在简单的ES6点击处理程序中遇到$(this)问题

时间:2017-12-05 17:10:38

标签: javascript jquery this

const letters = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","_"];

$.each(letters, (number, letter) => {
  let b = $('<button>');
   b.addClass('letter-button letter letter-button-color')
    .attr('data-let', letter)
    .text(letter);
   $('#buttons').append(b);
});
$('.letter-button').on('click', () =>  {
    let fridgeMagnet = $('<div>');
    fridgeMagnet.addClass('letter fridge-color')
    .text($(this).data('let'));
    console.log(this);
    $('#display').append(fridgeMagnet);
});

这是一个旧练习,解决方案是使用过时的JavaScript版本。我正在尝试将第4步和第5步更新为ES6,但$(this)在这里不起作用。任何人都可以向我解释如何修复点击处理程序以及$(this)如何从ES5更改为ES6?我们希望新创建的按钮显示在带有正确字母数据的背景冰箱图像上。此外,什么是“数据 - 让”?

1 个答案:

答案 0 :(得分:0)

由于$(this),你不能使用带有jquery envent处理程序的箭头函数,而箭头函数不是新函数。函数关键字id没有过时!使用function()unstead。

You Can refer to this blog post for more info