简体   繁体   中英

Calling a function from within nested functions in jQuery

I'm guessing this is a scope problem, but I can't work it out! I have a function which validates a form before sending. On submit, it iterates through each field and checks the details. It should then set a cookie for each value, since the form sends the user away from the site, temporarily, and I need that data when they return.

I have a set cookie function that works just fine, but calling this function from within two nested functions just does nothing.

$(document).ready(function() {
    $("form#mainRequestBrochure").submit(function(event) {
        event.preventDefault();     //prevent form.submit()
        var missingData = 0;        // missing required fields counter
        $("form#contactForm input").each(function(index) {
            var ok = 0;
            var v = $(this).val();
            var n = $(this).attr('name');   
            if(isBlank(v)===true) {         // if empty
                $(this).addClass("error");  // add error class
                missingData++;              // add one to  counter
            } else if(($(this).attr('type')==="email")&&(!isValidEmailAddress(v))) {
                $(this).addClass("error");  
                missingData++;
            } else if ($(this).hasClass("error")) {     // not empty but has had error class applied
                $(this).removeClass("error");           // clear error class
                ok = 1;
            } else {
                ok = 1; 
            }
            if(ok===1) createCookie(n,v,7);
        });
        createCookie('Testing2','test',7);
        // if no errors recorded, submit the form
        if(missingData === 0 ) $("form#mainRequestBrochure").submit();
    }); 

});

function createCookie(name,value,days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        var expires = "; expires="+date.toGMTString();
    }
    else var expires = "";
    document.cookie = name+"="+value+expires+"; path=/";
    alert('cookie ' + name + ' set.');
}

The code directly inside of $("form#mainRequestBrochure").submit(function(event) works fine, creating the cookie named Testing2 using createCookie('Testing2','test',7) , but when I place that same line of code within the .each() loop, it does nothing.

Like I say, I'm guessing this is a scope thing, but it's driving me up the wall....

将createCookie函数移出Submit函数。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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