简体   繁体   English

如何将多个事件处理程序添加到同一事件?

[英]how to add multiple event handlers to the same event?

I'm new to JavaScript and I'm trying to register 2 event handlers to the same event from two different functions, but no matter what I try one event handler overrides the other. 我是JavaScript的新手,我试图从两个不同的函数向同一事件注册2个事件处理程序,但是无论我尝试哪种操作,事件处理程序都会覆盖另一个事件处理程序。 Is there any way that I can register multiple event handlers from different functions? 有什么方法可以注册来自不同函数的多个事件处理程序?

In the code bellow I try to register two event handlers by pressing two buttons, but the handlers override each other. 在下面的代码中,我尝试通过按下两个按钮来注册两个事件处理程序,但是这些处理程序彼此覆盖。

 <p id="text">text</p> <p id="text1">text1</p> <button id="myBtn">text</button> <button id="myBtn1">text1</button> <script> document.getElementById("myBtn").addEventListener("click", foo); document.getElementById("myBtn1").addEventListener("click", bar); function foo() { var target = document.getElementById("text"); document.body.onkeypress = function(e){ animateElem(target); } } function bar() { var target = document.getElementById("text1"); document.body.onkeypress = function(e){ animateElem(target); } } function animateElem(elemFound){ var start = 0.3; var increment = 0.3; var id = setInterval(allOpacity, 100); function allOpacity() { if (start > 3) { clearInterval(id); elemFound.style.opacity = 0.5; } else { start = start + increment; elemFound.style.opacity = start % 1; } } } </script> 

You should use addEventListener() instead of onkeypress 您应该使用addEventListener()代替onkeypress

addEventListener allows adding more than a single handler for an event. addEventListener允许为一个事件添加多个处理程序。

document.body.onkeypress = function(e){...} will override the other function. document.body.onkeypress = function(e){...}将覆盖其他函数。

 <p id="text">text</p> <p id="text1">text1</p> <button id="myBtn">text</button> <button id="myBtn1">text1</button> <script> document.getElementById("myBtn").addEventListener("click", foo); document.getElementById("myBtn1").addEventListener("click", bar); function foo() { var target = document.getElementById("text"); document.body.addEventListener('keypress',(e)=>{ animateElem(target); }) } function bar() { var target = document.getElementById("text1"); document.body.addEventListener('keypress',(e)=>{ animateElem(target); }) } function animateElem(elemFound){ var start = 0.3; var increment = 0.3; var id = setInterval(allOpacity, 100); function allOpacity() { if (start > 3) { clearInterval(id); elemFound.style.opacity = 0.5; } else { start = start + increment; elemFound.style.opacity = start % 1; } } } </script> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM