从JavaScript中的内部函数返回?
我有一个jQuery支持的JavaScript函数,它迭代一个字段列表并检查它们是否为空;如果是,则阻止表单的提交从JavaScript中的内部函数返回?,javascript,jquery,Javascript,Jquery,我有一个jQuery支持的JavaScript函数,它迭代一个字段列表并检查它们是否为空;如果是,则阻止表单的提交 required_fields.forEach(function(field) { if (field.val() == '') { field.addClass('field-highlight'); return false; } else { field.removeClass('fiel
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
如何以不同的结构来完成我想要的任务?只需使用一个变量来跟踪验证:
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;
在forEach闭包中使用布尔值,如果字段值为空,则该值将设置为true。在提交表单之前检查该值听起来您想执行以下操作
var anyEmpty = false;
required_fields.forEach(function() {
if ($(this).value() == '') {
$(this).addClass('field-highlight');
anyEmpty = true;
} else {
$(this).removeClass('field-highlight');
}
});
if (anyEmpty) {
// Block the form
}
- 根据元素是否具有值,使用突出显示的
字段更新元素
- 如果任何表单为空,请阻止表单提交
如果是这样,请尝试以下方法
var anyEmpty = false;
required_fields.forEach(function() {
if ($(this).value() == '') {
$(this).addClass('field-highlight');
anyEmpty = true;
} else {
$(this).removeClass('field-highlight');
}
});
if (anyEmpty) {
// Block the form
}
您是否编写了“forEach”函数?如果是这样,则可以检查anon函数的返回值,如果返回值为false,则停止迭代。如果您的必填字段是jQuery对象,则可以执行以下操作:
var stop = required_fields.removeClass('field-highlight')
.filter("[value == '']").addClass('field-highlight')
.length;
return !!stop
或者像这样更有效率
var stop = required_fields.filter('.field-highlight').removeClass('field-highlight')
.end().filter("[value == '']").addClass('field-highlight')
.length;
return !!stop
forEach是jQuery助手function@Evan-它是API中未记录的部分吗?对不起,我写得很匆忙。我想到了这个:我在jQuery1.5路线图中看到了它