【问题标题】:How to stop function from running in javascript, jquery?如何阻止函数在 javascript、jquery 中运行?
【发布时间】:2010-01-21 21:24:05
【问题描述】:

我有以下功能:

function checkEmails(newEmail){
    $('table td:nth-child(3)').each(function(){
        if ($(this).html() == newEmail)
        {
            alert('The email address "' + newEmail + '" is already in the list.  Duplicates are not allowed.');
            toggleSpinner();
            return false;
        }           
    });
    return true;
} 

我在我的表单提交处理程序中这样调用它:

if (!checkEmails($('input#email', $('#newForm')).val())) {
  return false;
}//I submit the form via ajax next....

我只是在检查以确保用户尝试提交的电子邮件地址不在表格中。它似乎工作得很好,除了在 Firefox 中,它实际上并没有阻止 ajax 请求的发生。出现警告框,告诉我用户已经在列表中,但单击确定后,表单仍然提交。它可以在 IE 中按我想要的方式工作。

我在这里做错了什么?

【问题讨论】:

    标签: javascript jquery


    【解决方案1】:

    应该是这样的:

    function checkEmails(newEmail){
        var ret = true;
        $('table td:nth-child(3)').each(function(){
            if ($(this).html() == newEmail)
            {
                alert('The email address "' + newEmail + '" is already in the list.  Duplicates are not allowed.');
                toggleSpinner();
                ret = false;
            }           
        });
        return ret;
    } 
    

    它所做的是在对元素执行 each 之前将返回值设置为 true,然后如果它发现任何无效的电子邮件地址,它将把它设置为 false。那就是将从函数返回的值。

    【讨论】:

      【解决方案2】:

      return false 在闭包内部,因此它不会脱离外部函数

      即它为嵌套函数返回 false 而不是 checkEmails

      【讨论】:

        【解决方案3】:

        我想你想要这个(使用 bigFatGlobal 来存储返回值):

        function checkEmails(newEmail){
            var bigFatGlobal = true;
        
            $('table td:nth-child(3)').each(function(){
                if ($(this).html() == newEmail)
                {
                    alert('The email address "' + newEmail + '" is already in the list.  Duplicates are not allowed.');
                    toggleSpinner();
                    bigFatGlobal = false;
                }           
            });
            return bigFatGlobal;
        }
        

        【讨论】:

        • 那不是真正的全球性的吗?
        • 好吧,它不是 jQuery 调用的函数的本地函数。
        猜你喜欢
        • 1970-01-01
        • 2021-05-15
        • 1970-01-01
        • 2011-05-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-08-06
        相关资源
        最近更新 更多