簡體   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