当向匿名函数传递参数时,由于某种原因,每个元素的事件侦听器会触发两次。即,元素 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);
问题是为什么,以及有什么解决方案?
我在其他地方搜索,似乎找不到解决方案或者无法理解为什么出现这个问题。我尝试了在如何将参数传递给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>
非常感谢您的帮助。
el.addEventListener
两次? - Felix KlingaddEventListener()
,则监听器将运行两次。 - Barmar