javascript - 从 jQuery 到普通 JavaScript 的语法。功能不一样

标签 javascript jquery html

我在 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. The this value of the enclosing lexical scope is used; arrow functions follow the normal variable lookup rules. So while searching for this which is not present in current scope, an arrow function ends up finding the this 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/

相关文章:

javascript - 如何从 jQuery 触发鼠标移动事件

javascript - 如何根据绑定(bind)值在 Knockout.js 中隐藏按钮

Javascript 克隆元素

javascript - 如何在 Google App Engine 上存储 HTML 5 地理位置数据?

javascript - 将 React 组件数组传递给 useState 返回空数组

javascript - 缩小时如何阻止背景移动?

jquery 对话框 - 页面上有多个对话框,一次只能打开一个

html - 选择依赖于另一个选择 - Material Angular

javascript - Chart.js 使用 X 轴时间动态更新图表

javascript - Oracle Apex 18.1 Interactive Grid (IG) 以编程方式设置过滤器?自定义 IG 搜索