如何在提交表单时调用JS函数



我有这个代码来验证并提交一个联系表单:

form_valid: function() {
if (
this.form_data.nombre &&
this.form_data.empresa &&
this.form_data.email &&
this.form_data.rubro &&
this.form_data.telefono &&
this.form_data.consulta_por &&
this.form_data.msg &&
this.form_data.rcapt_response
) {
return true;
}
}

但当这个函数打开时,我需要调用另一个函数;真";。我不知道我是否能写:

return true;
return function2();

或者如果我需要写另一个检查过的函数:

if (form_valid() === true) {
function2();
}
function form_valid() {
const data = this.form_data
return (
data.empresa &&
data.email &&
data.rubro &&
data.telefono &&
data.consulta_por &&
data.msg &&
data.rcapt_response
)
}
// Return the result
return form_valid() && my_other_function()
// OR if you want to store the result in a variable instead of returning it
const result = form_valid() && my_other_function()

&&将继续执行,直到遇到错误值为止,因此如果form_valid()返回false,它将返回false,如果返回true,则调用my_other_function()。当然,if-语句也没有错,这只是一个可能的选项。

另一种选择可能是在form_valid()函数的末尾再链接一个&&,如下所示:return (... && data.rcapt_response && my_other_function()),但我不会这样做,除非它在逻辑上是确保表单有效的一部分。

将对其他函数的调用放入return语句中。

if (...) {
return function2();
}

当函数返回true时,此代码应为function2。

if(function()){
function2();
}