2013-06-13 23 views
0

我想要的方法来防止恢复他在做什么,如果条件不成立的代码。jQuery:如果通过别的死

这是我的代码

function doSomething{ 
    if(1==2){ 
     alert("Can I access to your event?"); 
    }else{ 
     //1 not equals 2, so please die 
     // I tried die() event; It worked, But i get this error in the console 
     // Uncaught TypeError: Cannot call method 'die' of undefined 
    } 
} 

$(".foo").click(function(){ 
    doSomething(); 
    alert("welcome, 1 == 1 is true"); 
} 
+0

JavaScript并没有一个死'()'默认功能。 –

+1

您是指[this](http://api.jquery.com/die/)? – PSL

+0

是的,这就是我的意思 –

回答

1

从代码来看,你可能想只是抛出一个异常;-)

function doSomething 
{ 
    if(1==2){ 
     alert("Can I access to your event?"); 
    }else{ 
     throw 'blah'; 
    } 
} 

这将展开栈立即直到异常被捕获或达到全球水平。

1

你可以只需点击处理程序中返回false,我想。例如:

function doSomething() { 
    if(1==2){ 
     alert("Can I access to your event?"); 
    }else{ 
     return false; // tell the click handler that this function barfed 
    } 
} 

$(".foo").click(function(){ 
    if(doSomething() === false){ //check to see if this function had an error 
     return false; //prevent execution of code below this conditional 
    } 
    alert("welcome, 1 == 1 is true"); 
} 
1

尝试这种传统方式

function doSomething() { 
    if(1==2){ 
     alert("Can I access to your event?"); 
     return true; 
    }else{ 
     return false 
    } 
} 

用法:

$(".foo").click(function(){ 
    if(doSomething()){ 
     alert("welcome, 1 == 1 is true"); 
    }else{ 
    alert("Sorry, 1 == 1 is false"); 
    } 

}

+0

http:// jsfiddle。网络/ tB5KY /概念验证感谢你:) – sksallaj

+0

@sksallaj对不起,没有得到它^ _^ –

+0

哈哈,noo,我的意思是我用你的解决方案,并实施它作为一个工作的例子..这一切:-) – sksallaj

0

你可以扔an exception

function doSomething(){ 
    if (1 == 2) { 
     alert("Can I access to your event?"); 
    } else { 
     throw "this is a fatal error"; 
    } 
} 

$(".foo").click(function() { 
    doSomething(); 
    alert("welcome, 1 == 1 is true"); 
}); 

FIDDLE

当然你应该处理例外日志中的不出现错误,也许像这样:

$(".foo").click(function() { 
    try { 
     doSomething(); 
     alert("welcome, 1 == 1 is true"); 
    } catch (err) { 
     // do nothing but allow to gracefully continue 
    } 
}); 

FIDDLE