停止 JavaScript 脚本执行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5075543/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Stop JavaScript script execution
提问by Hirvesh
I have a form which is being submitted by ajax. Before submission, there's a function which checks if a textarea in the form is empty before submitting. if it is empty, I need to stop the script and show a modal box AND prevent the submission of data to proceed.
我有一个由ajax提交的表单。在提交之前,有一个函数可以在提交之前检查表单中的文本区域是否为空。如果它是空的,我需要停止脚本并显示一个模式框并阻止提交数据以继续。
How do I stop execution? Do I use
如何停止执行?我用吗
break;
?
?
回答by dxh
Nope, you generally use return;
不,你通常使用 return;
Of course the exact details will vary depending on your implementation. You may need to return false;
, for instance, and manually check the return value to see whether or not to keep executing script in the calling function.
当然,具体细节会因您的实施而异。return false;
例如,您可能需要手动检查返回值以查看是否在调用函数中继续执行脚本。
回答by turbod
Try this:
尝试这个:
$('#target').submit(function() {
alert('Handler for .submit() called.');
return false;
});
回答by Zsub
You could use break;
but if you do you can't check return values (use return;
or return $bool;
for that).
您可以使用,break;
但如果您这样做,您将无法检查返回值(使用return;
或return $bool;
为此)。
I think a construction like this would do:
我认为这样的结构会做:
.submit(function ()
{
if (verifyInput())
{
// continue
}
else
{
// show user there is something wrong
}
});
verifyInput()
in this case would return a boolean, of course, representing wether or not the form was properly filled.
verifyInput()
在这种情况下,当然会返回一个布尔值,表示表单是否正确填写。
回答by mczepiel
While returning works well enough to prevent the default submit action, I would suggest calling event.preventDefault(). Simply call it first thing to prevent the user agent's default handling of that eventType. It's arguably the more modern way of doing this.
虽然返回可以很好地阻止默认提交操作,但我建议调用 event.preventDefault()。简单地首先调用它以防止用户代理对该事件类型的默认处理。这可以说是更现代的方式来做到这一点。
This of course assumes you have a reference to the event, which will be the first argument to your handler function or your EventListener object's handleEvent method so long as you provide a parameter for it.
这当然假设您有对事件的引用,只要您为其提供参数,这将是处理程序函数或 EventListener 对象的 handleEvent 方法的第一个参数。
It's just another tool to have in your toolbox, it also pairs nicely with event.stopPropagation, for when you don't want to stop the default but just want to stop event distribution.
它只是您工具箱中的另一个工具,它还可以与 event.stopPropagation 很好地配对,用于当您不想停止默认设置而只想停止事件分发时。