简体   繁体   English

防止两个事件相互触发

[英]Prevent two event's from firing right after each other

I have written a nonsensical program to demonstrate my problem. 我写了一个荒谬的程序来演示我的问题。

What should happen 应该发生什么

Pressing enter when the input field contains the word "text" displays the message "Don't change me until I'm ready" 当输入字段包含单词“ text”时,按Enter键将显示消息“在我准备好之前不要改变我”

waits for enter to be pressed again then clears the input field and display the message "Ha I changed you before you were ready" 等待再次按下Enter键,然后清除输入字段并显示消息“ Ha,在您准备好之前我已经改变了您”

What is happening 怎么了

Pressing enter when the input field contains the word "text" triggers both events one right after other other. 当输入字段包含单词“ text”时,按Enter会同时触发两个事件。

** what I have tried** **我尝试过的**

  • event.stopPropagation(); event.stopPropagation();
  • using a Boolean variable to add and remove the container event as needed. 使用布尔变量根据需要添加和删除容器事件。

however, neither have fixed the problem. 但是,都没有解决问题。

 const inputField = document.querySelector('.inputField'); const inform = document.querySelector('.inform'); const container = document.querySelector('.container'); inputField.addEventListener('keydown', function(event) { if (event.key === "Enter") { /*event.stopPropagation();*/ matchInput(); } }); function matchInput() { if (inputField.value === "text") inform.innerHTML = "Don't change me until i'm ready"; window.addEventListener("keydown", nextInput); }; function nextInput() { if (event.key === "Enter") { inputField.value = ""; inform.innerHTML = "Ha I changed you before you were ready!"; container.removeEventListener("keydown", nextInput); } }; 
 <div class="container"> <input type="text" name="" value="text" autofocus class="inputField"> <div class="inform"> </div> 

you're making your life difficult... (tio, te estás complicando la vida...). 您正在让自己的生活变得困难...(tio,teestáscomplicando la vida ...)。 Why don't you try with just one event handler: 为什么不尝试仅使用一个事件处理程序:

inputField.addEventListener('keydown', function(event) {
  if (event.key === "Enter") {
     if (inputField.value === "text") inform.innerHTML = "Don't change me until i'm ready";
     else {
        inputField.value = "";
        inform.innerHTML = "Ha I changed you before you were ready!";
     }
  }
});

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

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