从JavaScript中的内部函数返回? [英] Return from inner function in JavaScript?

查看:56
本文介绍了从JavaScript中的内部函数返回?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个jQuery驱动的JavaScript函数,它遍历一个字段列表并检查它们是否为空;如果是这样,则阻止提交表格。

I have a jQuery-powered JavaScript function which iterates over a list of fields and checks to see whether they are empty; if so, blocks the submission of the form.

required_fields.forEach(function(field) {
    if (field.val() == '')
    {
        field.addClass('field-highlight');
        return false;
    }
    else
    {
        field.removeClass('field-highlight');
    }
});

// I want to return to here from the return false point

我怎么能以不同的方式构建它来做我想要的呢?

How can I structure this differently to do what I want?

推荐答案

只需使用变量来跟踪验证:

Just use a variable to keep track of the validation:

var is_valid = true;

required_fields.forEach(function(field) {
    if (field.val() == '') {
        field.addClass('field-highlight');
        is_valid = false;
        return false;
    } else  {
        field.removeClass('field-highlight');
    }
});

return is_valid;

或者,您只需使用字段突出显示类:

required_fields.forEach(function(field) {
    if (field.val() == '') {
        field.addClass('field-highlight');
        return false;
    } else  {
        field.removeClass('field-highlight');
    }
});

return $('.field-highlight').length == 0;

这篇关于从JavaScript中的内部函数返回?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆