gpt4 book ai didi

javascript - addEventListener 在使用匿名函数传入参数时为同一个句柄触发多次

转载 作者:可可西里 更新时间:2023-11-01 02:52:49 26 4
gpt4 key购买 nike

出于某种原因,事件监听器在将参数传递给匿名函数时会为每个元素触发两次。即,元素 el 上的点击事件将注册一次,因此触发一次。

el.addEventListener("click", handle, false);
el.addEventListener("click", handle, false);

但如果我想将自己的参数传递给它,它会注册并触发两次。

el.addEventListener("click", function() { handle(event, myArgument); }, false);
el.addEventListener("click", function() { handle(event, myArgument); }, false);

问题是为什么以及解决方案是什么?

我看了其他地方,似乎无法找到解决方案或理解为什么会出现此问题。我尝试在 How to pass an argument to the listener function passed in addEventListener? 中实现解决方案,但它们没有帮助 --

我做了基本的匿名函数或闭包,然后是更高级的版本,如下所示,但它确实有效。

我不明白为什么不传递参数会导致元素事件注册一次,而传递参数会导致元素事件注册两次。

代码如下:

<html>
<head>
<script type="text/javascript">
var handle_2 = function(evt, type) {
var test;
switch (type) {
case "focus":
console.log(evt.target.value);
break;
case "click":
console.log(evt.target.id + " was clicked");
break;
default: console.log("no type found");
}
};

window.onload = function() {
var textbox = document.getElementById("t1");
var button = document.getElementById("btn");
textbox.value = "456";
button.value = "Press";

var typeFocus = "focus", typeClick = "click";

textbox.addEventListener("focus", (function(typeFocus) { return function(evt) { handle_2(evt, typeFocus); }})(typeFocus), false);
button.addEventListener("click", (function(typeClick) { return function(evt) { handle_2(evt, typeClick); }})(typeClick), false);

// Registers again for each element. Why?
textbox.addEventListener("focus", (function(typeFocus) { return function(evt) { handle_2(evt, typeFocus); }})(typeFocus), false);
button.addEventListener("click", (function(typeClick) { return function(evt) { handle_2(evt, typeClick); }})(typeClick), false);
};
</script>
</head>
<body>
<div id="wrapper">
<input id="t1" type="text" />
<input id="btn" type="button" />
</div>
</body>
</html>

如有任何帮助,我们将不胜感激。

最佳答案

最简单的解决方案是只创建一次新的处理程序:

var newHandle = function(event) { handle(event, myArgument); };

el.addEventListener("click", newHandle, false);
el.addEventListener("click", newHandle, false);

如果您在同一元素上多次调用 addEventListener,并且事件类型、处理程序和捕获的值完全相同,则处理程序只会注册一次。来自DOM spec :

...
5. If eventTarget’s event listener list does not contain an event listener whose type is listener’s type, callback is listener’s callback, and capture is listener’s capture, then append listener to eventTarget’s event listener list.
...

关于javascript - addEventListener 在使用匿名函数传入参数时为同一个句柄触发多次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26146108/

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