我有一个函数:
function myfunction() {
if (a == 'stop') // How can I stop the function here?
}
JavaScript中是否有类似exit()的东西?
我有一个函数:
function myfunction() {
if (a == 'stop') // How can I stop the function here?
}
JavaScript中是否有类似exit()的东西?
当前回答
function myfunction() {
if(a == 'stop')
return false;
}
返回错误;比只是回报要好得多;
其他回答
如果您正在寻找一个脚本,以避免在发现一些错误时提交表单,此方法应该有效
function verifyData(){
if (document.MyForm.FormInput.value.length == "") {
alert("Write something!");
}
else {
document.MyForm.submit();
}
}
将Submit Button类型更改为Button
<input value="Save" type="button" onClick="verifyData()">
希望这对你有所帮助。
使用一点不同的方法,你可以使用try catch和throw语句。
function name() {
try {
...
//get out of here
if (a == 'stop')
throw "exit";
...
} catch (e) {
// TODO: handle exception
}
}
这样的:
function myfunction()
{
if (a == 'stop') // How can I stop working of function here?
{
return;
}
}
显然你可以这样做:
function myFunction() {myFunction:{
console.log('i get executed');
break myFunction;
console.log('i do not get executed');
}}
通过使用标签查看块作用域:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/label
我还看不出有什么不好。但这似乎不是一种常用的用法。
推导出这个答案:JavaScript等价于PHP的die
如果你正在使用jquery。这将阻止函数冒泡到,因此父函数调用它也应该停止。
function myfunction(e)
{
e.stopImmediatePropagation();
................
}