繁体   English   中英

如果满足任何条件,forEach 循环不会检查数组中的所有项目

[英]forEach loop does not check all the items in the array if a condition is met in any of them

我有一个数组的forEach循环,但有一个 if 语句来检查输入是否为空。 问题是,如果找到一个空输入,循环就会停止,我希望它检查数组中的所有元素,即使 1 为空

这是我的代码

function showError(input, message) {
  const formControl = input.parentElement;
  formControl.className = "form-control error";
  const small = formControl.document.querySelector("small");
  small.inerText = message;
}
//show success message
function showSuccess(input) {
  const formControl = input.parentElement;
  formControl.className = "form-control success";
}

//check requiered fields

function checkRequired(inputArr) {
  inputArr.forEach(function(input) {

    if (input.value.trim() === "") {
      showError(input, "is required");
    } else {
      showSuccess(input);
    }
  });
}

// Event listener
form.addEventListener("submit", function(e) {
  e.preventDefault();
  checkRequired([username, email, password, password2]);
});

在此处输入图像描述]

您将 innerText 拼错为 inerText(因此作为您的提交按钮名称)。 从那里开始。 您的代码中有很多地方可能会发生异常,例如 checkRequired。 我的建议是从

small.innerText = message;

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM