繁体   English   中英

从jQuery的嵌套函数中调用函数

[英]Calling a function from within nested functions in jQuery

我猜这是一个范围问题,但我无法解决! 我有一个函数,可以在发送前验证表单。 在提交时,将遍历每个字段并检查详细信息。 然后,应该为每个值设置一个cookie,因为该表单会暂时将用户从网站上移开,并且在他们返回时我需要该数据。

我有一个set cookie函数,该函数可以正常工作,但是从两个嵌套函数中调用此函数却无济于事。

$(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.');
}

直接在$("form#mainRequestBrochure").submit(function(event)内部的代码可以正常工作,使用createCookie('Testing2','test',7)创建名为Testing2的cookie,但是当我将同一行.each()循环中的代码,它什么也不做。

就像我说的那样,我猜这是一个范围问题,但它使我无法自拔。

将createCookie函数移出Submit函数。

暂无
暂无

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

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