简体   繁体   English

如何将 click 事件的回调与 keydown 事件的回调结合起来?

[英]How can I combine the callback of the click event with the callback of the keydown event?

While I was coding, I have noticed that I am repeating the same code twice in two callback functions:在编码时,我注意到我在两个回调函数中重复了两次相同的代码:

document.querySelector(DOM.usernameInput).addEventListener("keydown", e => {
  if (e.keyCode === 13) {
    e.preventDefault();
    UI.events.form.password.show();
  }
});
document.querySelector(DOM.next).addEventListener('click', (e)=>{
    e.preventDefault();
    UI.events.form.password.show();
});

I have tried to write some algorithm which allows me to implement this goal, but still I am unable to reach that goal.我试图编写一些算法来实现这个目标,但我仍然无法达到那个目标。

Introduce a new function and move the common logic to that function.引入一个新功能并将通用逻辑移至该功能。

Please have a look.请看一看。

function showPassword(event) {
    event.preventDefault();
    UI.events.form.password.show();
}


document.querySelector(DOM.usernameInput).addEventListener("keydown", e => {
  if (e.keyCode === 13) {
   showPassword(e);
  }
});

document.querySelector(DOM.next).addEventListener('click', showPassword);

I Hope this helps you.我希望这可以帮助你。

Wrap the common code into a new function then call it from the others:将公共代码包装到一个新函数中,然后从其他函数中调用它:

function displayPassword() {
    UI.events.form.password.show();
}

document.querySelector(DOM.usernameInput).addEventListener("keydown", e => {
  if (e.keyCode === 13) {
    e.preventDefault();
    displayPassword();
  }
});

document.querySelector(DOM.next).addEventListener('click', (e)=>{
    e.preventDefault();
    displayPassword();
});

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

相关问题 Typescript:回调,其中事件可以是单击或 keydown throws 属性 'key' 在类型“事件”上不存在 - Typescript: callback where event can be click or keydown throws Property 'key' does not exist on type 'Event' 如何在事件单击时为 setState 编写回调函数 - How can I write callback func for setState on event click 如何结合点击事件和Enter键的按下状态? - How do I combine the on click event & the keydown of the enterkey? 点击事件中的回调 - Callback in click event 如何从JSDOM触发jQuery .on('click',选择器,回调)事件? - How to I trigger a jQuery .on('click', selector, callback) event from JSDOM? 我如何模拟点击或keydown事件? - How do i simulate a click or keydown event? 如何将带有多个参数的函数引用传递给jQuery(document).on('click'事件的回调? - How can I pass a function reference with multiple arguments to the callback of my jQuery(document).on('click' event? 如何将按钮单击事件传递给回调函数 - How to pass an event of a button click to a callback function 无论如何定义回调,如何删除事件侦听器 - How can I remove an event listener no matter how the callback is defined 为什么在keydown回调中返回false并没有停止按钮点击事件? - Why does returning false in the keydown callback does not stop the button click event?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM