jQuery:如果传递其他死亡

时间:2013-06-13 04:12:35

标签: javascript 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");
}

4 个答案:

答案 0 :(得分: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 :(得分:1)

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

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

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

答案 2 :(得分: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");
    }

}

答案 3 :(得分: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