Function called at the start of page loading - jav

2019-08-31 20:41发布

问题:

I have a problem; for some reason, my function is being called at the start of the webapplication while the page is loading.

My code is as follows

function validateName(element) {
        var len = element.value.length;

        //checks if the code is than 6 characters
        if (len == 0) { 
            element.style.backgroundColor="red";     
            if (element.id == "firstname")
            {
                document.getElementById('firstNameError').style.display = "block"; 
            }
            else if (element.id == "lastname") {
                document.getElementById('lastNameError').style.display = "block";                 
            }
            return true;
        } //if == 0
        else {
            element.style.backgroundColor="green";    
            if (element.id == "firstname")
            {
                document.getElementById('firstNameError').style.display = "none"; 
            }
            else if (element.id == "lastname") {
                document.getElementById('lastNameError').style.display = "none";                 
            }
        return false;
        } // if != 0
}

The logic of this function is to validate the text boxes where the user enters their name. Basically,the problem i am facing is as soon as I open up my web page, the text boxes are red, and say 'Your first name cannot be blank!' (which is the firstNameError). Then, once I enter the text in my text box, it doesn't change, it still stays red, and displays the error.

This is how i am calling the function:

function init() {
    var firstName = initToolTip("firstname", "firstnameTip");
    var lastName = initToolTip("lastname", "lastnameTip");
    var promoCode = initToolTip("promocode", "promocodeTip");
    //opens the TOS window when you click 'terms and conditions' link
    document.getElementById("clickedTOS").onclick = function() { sAlert(document.getElementById("TOS").innerHTML) };
    //checks the length of the promo code
    promoCode.onblur = validatePromoCode(promoCode);
    //checks the validity of a name (is not blank)
    firstName.onblur = validateName(firstName);
    lastName.onblur = validateName(lastName);
    //document.getElementById('submitButton').onmousedown = validateForm();
}

I don't understand why it's being called as soon as the page loads, since it's set, to be called onblur. can anyone suggest ways to fix this?

回答1:

You need to pass function references to onblur, not the result of immediately calling a function. Change to this:

function init() {
    var firstName = initToolTip("firstname", "firstnameTip");
    var lastName = initToolTip("lastname", "lastnameTip");
    var promoCode = initToolTip("promocode", "promocodeTip");
    //opens the TOS window when you click 'terms and conditions' link
    document.getElementById("clickedTOS").onclick = function() { sAlert(document.getElementById("TOS").innerHTML) };
    //checks the length of the promo code
    promoCode.onblur = function() {validatePromoCode(promoCode);};
    //checks the validity of a name (is not blank)
    firstName.onblur = function() {validateName(firstName);};
    lastName.onblur = function() {validateName(lastName);{;
    //document.getElementById('submitButton').onmousedown = validateForm();
}

This changes each onblur assignment to take an anonymous function reference that will be executed later when the onblur event happens, not immediately like your current code was doing.



回答2:

You're not passing the function to onblur in init; you are passing the result of the function.

See the following example:

var Afuntion=function(){
  console.log("hello from function");
  return 22;
}
Element.onblur=Afunction("something");//Element.onblur is now 22 and 
  // "hello from function" is logged
Element.onblur=Afunction; //now onblur has a reference to the function
Element.onblur();//this will log "hello from function" and return 22

Youre not using a library like jQuery to make attaching/adding event listeners easy so it's a bit of a pain to set the event listener using pure JS and read the event in the function. There must be some info on SO how to do this already anyway

In your case you could try this:

promoCode.onblur = function(){ validatePromoCode.call(promoCode,promCode);};