[英]I am unable to refactor my code for reusability
I want to extract the call back function into a separate function so I can reuse it without typing manually wherever I need to use it but am unable to achieve the desired result.我想将回调 function 提取到单独的 function 中,这样我就可以重用它而无需在需要使用它的任何地方手动输入,但无法达到预期的结果。 pls I need help am just new to javascript.
请我需要帮助,我是 javascript 的新手。 Below is my my attempt and the main code.
以下是我的尝试和主要代码。
const nav = document.querySelector('.nav');
const registerSection = document.querySelector('.register-section');
const loginSection = document.querySelector('.login-section');
const aboutUsSection = document.querySelector('.about-us-section');
const showForm = function (e, cl) {
if (!e.target.classList.contains(`${cl}`)) return;
loginSection.classList.add('hide-section');
aboutUsSection.classList.add('hide-section');
registerSection.classList.remove('hide-section');
};
nav.addEventListener('click', showForm.bind('list-link-register'));
nav.addEventListener('click', showForm.bind('list-link-login'));
// This is the code I wanted to refactor
nav.addEventListener('click', function (e) {
if (!e.target.classList.contains('list-link-register')) return;
loginSection.classList.add('hide-section');
aboutUsSection.classList.add('hide-section');
registerSection.classList.remove('hide-section');
});
nav.addEventListener('click', function (e) {
if (!e.target.classList.contains('list-link-login')) return;
aboutUsSection.classList.add('hide-section');
registerSection.classList.add('hide-section');
loginSection.classList.remove('hide-section');
});
Since you already have an if
statement you could put both cases in the same function由于您已经有了
if
语句,您可以将两种情况放在同一个 function
nav.addEventListener('click', function (e) {
if (e.target.classList.contains('list-link-register')){
aboutUsSection.classList.add('hide-section');
registerSection.classList.add('hide-section');
loginSection.classList.remove('hide-section');
}
if (e.target.classList.contains('list-link-login')) {
loginSection.classList.add('hide-section');
aboutUsSection.classList.add('hide-section');
registerSection.classList.remove('hide-section');
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.