0

如果条件不成立,我想要方法来防止代码恢复他正在做的事情。

这是我的代码

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");
}
4

4 回答 4

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");
}
于 2013-06-13T04:18:44.830 回答
1

从代码来看,您可能只想抛出异常 ;-)

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

这将立即展开堆栈,直到异常被捕获或达到全局级别。

于 2013-06-13T04:23:33.010 回答
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");
    }

}

于 2013-06-13T04:26:46.337 回答
0

你可以抛出一个异常

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");
});

小提琴

当然,您应该处理该异常,以免在日志中出现错误,可能像这样:

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

小提琴

于 2013-06-13T04:28:53.293 回答