Javascript 为什么我的jQuery函数没有被正确调用?
我有一个jQuery函数,它使用另一个jQuery库html5csv.js(这解释了您将看到的一些CSV内容) 这是:Javascript 为什么我的jQuery函数没有被正确调用?,javascript,jquery,onsubmit,Javascript,Jquery,Onsubmit,我有一个jQuery函数,它使用另一个jQuery库html5csv.js(这解释了您将看到的一些CSV内容) 这是: function validateNewQuiz() { CSV.begin("#upload_csv").go(function(e,D) { if (e) { return console.log(e); alert("Sorry, an error occured");
function validateNewQuiz()
{
CSV.begin("#upload_csv").go(function(e,D)
{
if (e)
{
return console.log(e);
alert("Sorry, an error occured");
}
var s = "";
for (var i = 0; i <= D.rows.length - 1; i++)
{
s +=D.rows[i].join(',');
s += "\n";
}
var fullString = s;
if(/^(([^,]+,){4}[^,]+\n){3}$/.test(fullString))
{
return true;
}
else
{
return false;
}
});
}
我的函数和正则表达式都经过了彻底的测试,以确保它正常工作。当我决定将其实现到我的大文档中,并将其包装在函数validatenewquick(){//my function here}
周围时,它停止了工作
我也没有使用表单中的onsubmit
部分进行测试
是否有人对为什么我的表单总是提交有任何建议,即使我的函数应该返回
false
?您可以制作一个按钮来调用您的函数:
<button onclick="validateNewQuiz()">Submit</button>
onsubmit
事件处理程序允许在验证函数传递true
值的情况下继续提交,如果收到false
值,则不允许继续提交。在您的情况下,内部函数返回true或false值,但该值不会传递给外部validatenewquick
函数,因此验证的true/false结果不会传递给onsubmit
事件处理程序。要解决此问题,只需返回CSV
函数的值
function validateNewQuiz()
{
var csvValidation = CSV.begin("#upload_csv").go(function(e,D)
{
if (e)
{
return console.log(e);
alert("Sorry, an error occured");
}
var s = "";
for (var i = 0; i <= D.rows.length - 1; i++)
{
s +=D.rows[i].join(',');
s += "\n";
}
var fullString = s;
if(/^(([^,]+,){4}[^,]+\n){3}$/.test(fullString))
{
return true;
}
else
{
return false;
}
});
return csvValidation;
}
函数validatenewquick()
{
var csvValidation=CSV.begin(“#upload_CSV”).go(函数(e,D)
{
如果(e)
{
返回控制台.log(e);
警报(“对不起,发生了错误”);
}
var s=“”;
对于(var i=0;i),您正在从传递到go()
的回调函数返回true
或false
,因此validatenewquick
实际上返回未定义。如果CSV库是异步的(看起来是异步的),您将无法在onsubmit处理程序中以这种方式使用它。@MattGreer-您还有其他选择吗?在将表单客户端发布到myPHP
之前,我需要使用Javascript验证表单客户端。您的外部函数validateNewQuit()实际上没有返回任何内容。您只是返回CSV函数的值,然后什么也不做。让ValidateNewQuit()fn实际返回CSV函数的值。@gos1-您可以在“答案”部分中发布一个这样的示例吗?您有jQuery-为什么要添加内联事件处理程序?
function validateNewQuiz()
{
CSV.begin("#upload_csv").go(function(e,D)
{
//...
if(/^(([^,]+,){4}[^,]+\n){3}$/.test(fullString))
{
$("form").submit();
}
});
return false;
}
function validateNewQuiz()
{
var csvValidation = CSV.begin("#upload_csv").go(function(e,D)
{
if (e)
{
return console.log(e);
alert("Sorry, an error occured");
}
var s = "";
for (var i = 0; i <= D.rows.length - 1; i++)
{
s +=D.rows[i].join(',');
s += "\n";
}
var fullString = s;
if(/^(([^,]+,){4}[^,]+\n){3}$/.test(fullString))
{
return true;
}
else
{
return false;
}
});
return csvValidation;
}