如何在循环中使用它?

时间:2019-04-26 13:10:19

标签: javascript

我正在为类分配作业,我知道必须有一种更好的编写方式。也许某种获取输入和标签的循环?我在这里重复很多,如果可能的话,最好将其最小化。

function checkEmptyFields() {

if(formName.value === "") {        
    formLabels[0].classList.add("has-errors");
    formLabels[0].innerHTML = "Name is required *";
    formName.style.borderBottomColor = "red";
} else {
    formLabels[0].classList.remove("has-errors");
    formLabels[0].innerHTML = "Name";
    formName.style.borderBottomColor = "green";
}

if(formEmail.value === "") {
    formLabels[1].classList.add("has-errors");
    formLabels[1].innerHTML = "Email is required *";
    formEmail.style.borderBottomColor = "red";
} else {
    formLabels[1].classList.remove("has-errors");
    formLabels[1].innerHTML = "Email";
    formEmail.style.borderBottomColor = "green";
}

if(formNumber.value === "") {
    formLabels[2].classList.add("has-errors");
    formLabels[2].innerHTML = "Phone is required *";
    formNumber.style.borderBottomColor = "red";
} else {
    formLabels[2].classList.remove("has-errors");
    formLabels[2].innerHTML = "Phone";
    formNumber.style.borderBottomColor = "green";
}

if(formMessage.value === "") {
    formLabels[3].classList.add("has-errors");
    formLabels[3].innerHTML = "message is required *";
    formMessage.style.borderBottomColor = "red";
} else {
    formLabels[3].classList.remove("has-errors");
    formLabels[3].innerHTML = "Email";
    formMessage.style.borderBottomColor = "green";
}
}

5 个答案:

答案 0 :(得分:2)

您可以尝试这样:

fields = [{
 'name': formName,
 'index': 0,
 'css-error': "has-errors",
 'innerHtml': "Name",
 'innerHtml-error': "Name is required *",
 'borderBottomColor ': "green", //Or you can hardcode it in the loop itself.
 'borderBottomColor-error': "red"
},
 ....
]

for(var i=0; i < fields.length; i++) {
 var field = fields[i];
 if(field.name.value == "") {
   formLabels[field.index].classList.add(field.css);
   formLabels[field.index].innerHTML = field.innerHtml-error;
   field.name.style.borderBottomColor = field.borderBottomColor-error ;
 } else {
   formLabels[field.index].classList.remove(field.css);
   formLabels[field.index].innerHTML = field.innerHtml;
   field.name.style.borderBottomColor = field.borderBottomColor ;
 }
}

答案 1 :(得分:1)

您可以为控件控件名称创建数组,并与您已经拥有的formLabels数组一起在< em> for 循环从0到长度(不包括在内),如下所示:

function checkEmptyFields() {

    var controls = [formName, formEmail, formNumber, formMessage];
    var controlNames = ["Name", "Email", "Phone", "Message"];

    for (var i = 0; i < controls.length; i++) {
        if(controls[i].value === "") {        
            formLabels[i].classList.add("has-errors");
            formLabels[i].innerHTML = controlNames[i] + " is required *";
            controls[i].style.borderBottomColor = "red";
        } else {
            formLabels[i].classList.remove("has-errors");
            formLabels[i].innerHTML = controlNames[i];
            controls[i].style.borderBottomColor = "green";
        }
    }
}

答案 2 :(得分:0)

您可以编写其他功能来检查一个字段:

    function checkEmptyField(field, ind, msg, errmsg) {

    if(field.value === "") {        
        formLabels[ind].classList.add("has-errors");
        formLabels[ind].innerHTML = errmsg;
        field.style.borderBottomColor = "red";
    } else {
        formLabels[ind].classList.remove("has-errors");
        formLabels[ind].innerHTML = msg;
        field.style.borderBottomColor = "green";
    }
    }

然后您可以调用它

function checkEmptyFields() {
 checkEmptyField(formName,0,"Name","Name is required *");
...

答案 3 :(得分:0)

如果您了解并了解循环,则可以简单地循环2个数据数组,如下所示:

function checkEmptyFields() {

    formArray = [formName, formEmail, formNumber, formMessage];
    labelArray = ["Name", "Email", "Phone", "Message"];

    for (let i = 0; i < formArray.length; i++) {
        if(formArray[i].value === "") {        
            formLabels[i].classList.add("has-errors");
            formLabels[i].innerHTML = labelArray[i] + " is required *";
            formArray[i].style.borderBottomColor = "red";
        } else {
            formLabels[i].classList.remove("has-errors");
            formLabels[i].innerHTML = labelArray[i];
            formArray[i].style.borderBottomColor = "green";
        }
    }
}

如果没有,那么您可以在这里阅读有关它们的信息:

https://www.w3schools.com/js/js_loop_for.asp

答案 4 :(得分:0)

任何时候,只要您在一个以上的地方拥有大致相同的代码,就应该像在这里一样停下来并重新思考您的方法。

如果为每个需要验证的HTML元素提供一个公共类,则可以创建一个包含它们的节点列表(集合/数组)。然后,您可以遍历该集合,并对每个项目执行相同的测试(仅编写一次),并采取相应的行动。

此外,我不太确定您在使用.innerHTML是做什么的,但是当您使用的文本中没有任何HTML时,请不要使用它。 .innerHTML具有安全性和性能影响。如果没有HTML,请使用.textContent

// Get all the form fields that need validation into an Array
let fields = Array.prototype.slice.call(document.querySelectorAll(".validationNeeded"));

// Set up form submit event handler
document.querySelector("form").addEventListener("submit", checkEmptyFields);

function checkEmptyFields(event) {
  let validCount = fields.length; // Holds the number of valid fields

  // Loop over the array
  fields.forEach(function(field){
    if(field.value === ""){
      field.previousElementSibling.classList.add("has-errors-label");    // style the label
      field.classList.add("has-errors-field"); // style the field
      field.classList.remove("valid-field");   // style the field        
      validCount--; // Decrease the count of valid fields
    } else {
      field.previousElementSibling.classList.remove("has-errors-label"); // style the label
      field.classList.remove("has-errors-field"); // style the field
      field.classList.add("valid-field");         // style the field       
    }
  });
  
  // Check to see if the form should be submitted
  if(validCount !== fields.length){
    event.preventDefault();  // Cancel the form's submission
  }
}
.row {margin-bottom:5px; }
.has-errors-label { color:red; }
.has-errors-field { outline:1px solid red; }
.valid-field      { outline:1px solid green; }
<form action="#" method="get">
  <div class="row">
    <label for="userName">Name: </label>
    <input class="validationNeeded" name="userName" id="userName">
  </div>
  <div class="row">
    <label for="email">Email: </label>
    <input class="validationNeeded" name="email" id="email">
  </div>
  <div class="row">
    <label for="phone">Phone: </label>
    <input class="validationNeeded" name="phone" id="phone">
  </div>
  <button>Submit</button>
</form>