相同的addEventListener可以工作吗? [英] Will the same addEventListener work?
问题描述
elemen.addEventListener('click',func,false);
elemen.addEventListener('click',func,false);
func
是否会在两次调用单击元素
?
Will whether the func
be called twice on click on elemen
?
如果是,是否有解决方案来检查是否存在相同的事件侦听器元素
?
If yes... Is there a solution to check is the same event listener exists on elemen
?
推荐答案
func
不会在点击时被调用两次,不会,不会;但请继续阅读以获取详细信息和陷阱。
func
will not be called twice on click, no; but keep reading for details and a "gotcha."
来自 addEventListener
在规范中:
From addEventListener
in the spec:
如果在相同的
EventTarget $上注册了多个相同的
EventListeners
c $ c>具有相同参数的重复实例将被丢弃。它们不导致EventListener
被调用两次,并且由于它们被丢弃,因此不需要使用删除它们。 removeEventListener
方法。
If multiple identical
EventListeners
are registered on the sameEventTarget
with the same parameters the duplicate instances are discarded. They do not cause theEventListener
to be called twice and since they are discarded they do not need to be removed with theremoveEventListener
method.
(我的重点)
下面是一个示例:
var target = document.getElementById("target");
target.addEventListener("click", foo, false);
target.addEventListener("click", foo, false);
function foo() {
var p = document.createElement("p");
p.innerHTML = "This only appears once per click, but we registered the handler twice.";
document.body.appendChild(p);
}
<input type="button" id="target" value="Click Me">
但是要注意的是,它必须是相同的功能,而不仅仅是功能相同的功能。例如,在这里我将四个单独的函数连接到元素,所有这些函数都将被调用:
It's important to note, though, that it has to be the same function, not just a function that does the same thing. For example, here I'm hooking up four separate functions to the element, all of which will get called:
var target = document.getElementById("target");
var count;
for (count = 0; count < 4; ++count) {
target.addEventListener("click", function() {
var p = document.createElement("p");
p.innerHTML = "This gets repeated.";
document.body.appendChild(p);
}, false);
}
<input type="button" id="target" value="Click Me">
这是因为在每次循环迭代中,都是不同的函数被创建(即使代码相同)。
That's because on every loop iteration, a different function is created (even though the code is the same).
这篇关于相同的addEventListener可以工作吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!