【问题标题】:Calling a function from within nested functions in jQuery从 jQuery 的嵌套函数中调用函数
【发布时间】:2012-02-23 09:09:32
【问题描述】:

我猜这是一个范围问题,但我无法解决!我有一个在发送之前验证表单的功能。在提交时,它会遍历每个字段并检查详细信息。然后它应该为每个值设置一个 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() 循环中时,它什么也不做。

就像我说的,我猜这是一个范围的事情,但它把我逼到了墙角......

【问题讨论】:

  • 应该将“form#contactForm input”改为“form#mainRequestBrochure input”吗?
  • 错误在于您的 createCookie 方法。向我们展示该代码
  • 已添加,请参见上文。我觉得没问题...
  • whererhys -- 天哪,我不敢相信我犯了这样的错误。你是绝对正确的。在草率的编码人员之后,剪切粘贴是有史以来最糟糕的事情。

标签: javascript jquery scope each


【解决方案1】:

将 createCookie 函数移到提交函数之外。

【讨论】:

    猜你喜欢
    • 2018-03-13
    • 2012-11-20
    • 2015-05-24
    • 2010-11-23
    • 1970-01-01
    • 2018-05-27
    • 1970-01-01
    • 2011-10-22
    • 2017-12-02
    相关资源
    最近更新 更多