javascript - 事件处理语法

标签 javascript

我正在阅读关于 Eloquent JavaScript 中的处理事件的书,他们有这个例子来解释 stopPropagation:

let para = document.querySelector('p');
let button = document.querySelector('button');

para.addEventListener('mousedown', () => {
  console.log("Handler for paragraph.");
})
button.addEventListener('mousedown', event => {
  console.log("Handler for button.");
  if (event.button == 2) event.stopPropagation();
})
<p>A paragraph with a <button>button</button>.</p>

我不明白为什么,当他们将事件监听器添加到 para 变量时,他们用 () => 编写它

para.addEventListener('mousedown', () => {})

当他们将其添加到按钮变量时,他们将其编写为事件 =>

button.addEventListener('mousedown', event => {})

我尝试将 () => 添加到按钮变量,代码的工作方式与使用 event => 时一样。这只是为了让我们记住这两种用途吗?还是有一个我只是想念的正当理由?

谢谢!

最佳答案

I couldn't get why, when they added event listener to para variable they were writing it with () =>

事件处理程序将事件对象作为其第一个参数传递。由于该函数没有使用它,因此它没有在参数列表中捕获它。

And when they were adding it to the button variable, they were writing it as event =>

该函数确实使用了Event对象,因此它被捕获在参数列表中。

've tried adding the () => to the button variable, and the code works just as it did with event =>. Is this just so we could remember both uses? Or is there a valid reason for this that I'm just missing?

现在您正在使用global event object MDN 说:

You should avoid using this property in new code, and should instead use the Event passed into the event handler function. This property is not universally supported and even when supported introduces potential fragility to your code.

关于javascript - 事件处理语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54317524/

相关文章:

javascript - 使用 Flow.js 在 React 中自动完成自定义按钮组件的 vs-code

javascript - 使用 Chart.js 和 CSV 数据绘制折线图

javascript - AngularJS 指令隔离范围不更新父级

javascript - 使用 JSON 在 php 中附加一个文本文件,不起作用并且没有显示错误消息

javascript - d3 刻度轴两侧的刻度线

javascript - 如何使用 JS/CSS/HTML5 动画来获得类似 Flash 的动画?例如 PagePeel

javascript - 嵌套的 For 循环转换为嵌套的 Promises

javascript - 通过三元运算符进行自分配

javascript - 如何禁止 ESLint 将项目添加到 useEffect 的观察者数组中?

javascript - 禁用 div 内的表单元素