gpt4 book ai didi

javascript - 事件处理语法

转载 作者:行者123 更新时间:2023-12-03 00:20:56 24 4
gpt4 key购买 nike

我正在阅读关于 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com