我在 jQuery 中有以下代码:
$("#input").change(function(){
var input = this;
console.log(input);
});
当输入发生更改时,该元素将在控制台中显示为 html。 我尝试将其更改为纯 JavaScript,如下所示:
var img = document.getElementById('input');
img.addEventListener( 'change' , () => {
var input = this;
console.log(input);
});
这里控制台中的输出是整个 html 文档,而不仅仅是输入元素。有人可以向我解释为什么会发生这种情况吗?
谢谢!
最佳答案
来自docs
An arrow function does not have its own
this
. Thethis
value of the enclosing lexical scope is used; arrow functions follow the normal variable lookup rules. So while searching forthis
which is not present in current scope, an arrow function ends up finding thethis
from its enclosing scope.
因此,在这种情况下您需要做的一切:
var img = document.getElementById('input');
img.addEventListener( 'change' , function () {
var input = this;
console.log(input);
});
关于javascript - 从 jQuery 到普通 JavaScript 的语法。功能不一样,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59789749/