简体   繁体   English

如何检查所有箭头功能是否都是真的?

[英]How to check if all arrow functions are true?

I'm creating a form validator. 我正在创建一个表单验证器。 And I only want to go to the next page if all four validators are true. 如果所有四个验证器都是真的,我只想进入下一页。 I've created four arrow functions for the validators. 我为验证器创建了四个箭头函数。

const nameIsValid = name => !name.match(nameRegX);
const mailIsValid = mail => mail.match(mailRegX);
const phoneIsValid = phone => phone.match(phoneRegX);
const postalIsValid = postal => postal.match(postRegX);

Every arrow function is tied to a event listener onchange in the input. 每个箭头函数都与输入中的事件监听器onchange绑定。 This looks like this. 这看起来像这样。

inputs[0].onchange = function() {
    var validateName = nameIsValid(name.value);
    animator(validateName, 0, isNameTrue);  
}

Then all four times inputs[1], [2] & [3]. 然后全部四次输入[1],[2]和[3]。

In the function you see the third argument of the animator is isNameTrue. 在函数中,您看到动画师的第三个参数是isNameTrue。 These are variables I've declared before the function with this: 这些是我在函数之前声明的变量:

var isNameTrue = false;
var isMailTrue = false;
var isPhoneTrue = false;
var isPostalTrue = false;

Then if the arrow function is true, I want to turn these values true as well, which I do by this function. 然后,如果箭头函数为true,我想将这些值也设置为true,这是我通过此函数执行的操作。

function animator(validity, i, isTrue){
    var error = document.querySelectorAll(".form-error");
    var correct = document.querySelectorAll(".form-display");

    if (validity){
        correct[i].classList.add("animate")
        error[i].classList.remove("animate")
        isTrue = true;


    } else {
        error[i].classList.add("animate")
        correct[i].classList.remove("animate")
        isTrue = false;
    }
}

Then when the user clicks on the submit button, I only want the next action when all four are true. 然后,当用户单击提交按钮时,我只想要在所有四个都为真时执行下一个操作。

inputs[4].onclick = function(){
    if (isNameTrue && isMailTrue && isPhoneTrue && isPostalTrue){
        console.log("We are all true");
    } else {
        console.log("We are not true!")
    }

}

However, they're always false. 但是,它们总是错误的。

How can I properly check if all four are true? 我怎样才能正确检查这四个是否属实?

boolean are passed by value,hence, the reference is not same which means even if you change the value in the animator function, the value of the variable passed will not change. boolean是按值传递的,因此,引用不相同,这意味着即使您更改animator函数中的值,传递的变量的值也不会更改。

You can update your code to following 您可以将代码更新为以下内容

inputs[0].onchange = function() {
    var validateName = nameIsValid(name.value);
    isNameTrue = validateName; // <---- Set your value here and do not pass to the function
    animator(validateName, 0);  
}

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

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