javascript 我怎样才能使这个JS代码更简单的帮助!太多的if语句[关闭]

ktca8awb  于 2022-12-02  发布在  Java
关注(0)|答案(2)|浏览(122)

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");
    }
}
r3i60tvu

r3i60tvu1#

试试这个

const validateInput = (elm) => elm.value.trim().length > 0;
const handleInput = (elm) => {
    const isValid = validateInput(elm);
    elm.classList.toggle("error", !isValid);
    return isValid;
}

小提琴:https://jsfiddle.net/codeandcloud/jr5aym6q/

pdkcd3nj

pdkcd3nj2#

您的意思是将它们缩短为DRY吗?
我看到两个函数非常相似,因此你可以重用它们,特别是验证部分和添加/删 debugging 误类。之后,你可以重用任何新的输入函数。
但是记住不要过度使用它,只要它对你和人们来说是可读的,并且你可以维护它。

const isInputValid = element => element.value.trim().length > 0

const validateInputElement = inputElement => {
  if (!isInputValid(inputElement)) {
    inputElement.classList.add('error')
  } else {
    // not valid
    inputElement.classList.remove('error')
  }
}

const handleInputName = () => {
  validateInputElement(document.getElementById('name'))
}

const handleInputMail = () => {
  validateInputElement(document.getElementById('email'))
}

相关问题