[英]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.