Closed. This question needs details or clarity . It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post .
Closed 1 hour ago.
Improve this question
Im a rookie in coding, an im figuring a way to shorten this code, it has too many if statements, if someone can help me out, i really apreciatted. I need to add a classList.remove to the same elements too after that
So this is the code:
const inputElementName = document.getElementById("name");
const inputElementMail = document.getElementById("email");
const validateInputName = () => inputElementName.value.trim().length > 0;
const validateInputMail = () => inputElementMail.value.trim().length > 0;
const handleInputName = () => {
const inputNameIsValid = validateInputName();
if (!inputNameIsValid) {
return inputElementName.classList.add("error");
}
}
const handleInputMail = () => {
const inputMailIsValid = validateInputMail();
if (!inputMailIsValid) {
return inputElementMail.classList.add("error");
}
}
2条答案
按热度按时间r3i60tvu1#
试试这个
小提琴:https://jsfiddle.net/codeandcloud/jr5aym6q/
pdkcd3nj2#
您的意思是将它们缩短为DRY吗?
我看到两个函数非常相似,因此你可以重用它们,特别是验证部分和添加/删 debugging 误类。之后,你可以重用任何新的输入函数。
但是记住不要过度使用它,只要它对你和人们来说是可读的,并且你可以维护它。