首页 > 解决方案 > 在文本框中键入时,JavaScript/jquery 运行按钮按下事件

问题描述

我正在做一个网络应用程序,但在不激活与按键相关的 JavaScript 事件的情况下,我无法在文本框中输入内容。我尽力想办法在专注于文本框的同时禁用所有这些事件,但无济于事。有没有办法“关注”文本框以阻止其他事件运行?谢谢。

标签: javascriptjquery

解决方案


试试下面的代码。focus删除所有事件侦听器并onblur添加所有事件侦听器。

let input = document.getElementById('input');
  
  //Attach all the events
  input.addEventListener('focus', removeAllEventListner);
  input.addEventListener('keypress', myFunction);
  input.addEventListener('blur', addEvents);
  
  //On focus remove all the events
  function removeAllEventListner() {
    input.removeEventListener('keypress', myFunction);
    console.log('Event removed');
  }

 //Onblur add all event 
  function addEvents() {
    input.addEventListener( 'onkeypress', myFunction);
    console.log('Event attached');
  }

  function myFunction() {
    console.log('Keypress event');
  }
<input type="text" id="input"  value="" >

希望这能解决问题。


推荐阅读