$(this)如何不能成为在jQuery单击处理程序中触发事件的元素? [英] how can $(this) not be the element that triggered the event in a jquery click handler?

查看:72
本文介绍了$(this)如何不能成为在jQuery单击处理程序中触发事件的元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的点击处理程序

I have a simple click handler

<h1 id="test">

$('#test').click( ev => {
   var $test = $(this);
   console.log($test.text());
})

,但不起作用,$(this)不是发射器元素.如果我检查this,我会看到一个窗口"(?)(??)(??!)

but it does not work, $(this) is not the emitter element. If I inspect this I see a "window" (?) (??) (??!)

此外,如果我将代码更改为

also, if I change my code to

var $test = $(ev.toElement);

它完美地工作.

怎么可能?我的代码中有什么阻止jquery正确传递this中的元素?

how can this be? what is in my code that prevents jquery to correctly pass the element in this ?

推荐答案

箭头功能不绑定thisarguments等.

Arrow functions do not bind this, arguments etc. MDN.

箭头函数表达式的语法比函数短 表达式并按词法绑定this值(不绑定其自身的 thisargumentssupernew.target).

An arrow function expression has a shorter syntax compared to function expressions and lexically binds the this value (does not bind its own this, arguments, super, or new.target).

这篇关于$(this)如何不能成为在jQuery单击处理程序中触发事件的元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆