4

我是否可以根据内部 if 语句的条件中止函数的其余部分而不使用 else 条件?

下面的代码示例。

("#btn").click(function(){
    if(name == call_name){
     alert(err)
    }

    //abort the rest of the function below without the need for else
});

谢谢你。

4

3 回答 3

4

您可以使用 return 语句来短路函数。

("#btn").click(function(){
    if(name == call_name){
     alert(err)
     return false;
    }

    //abort the rest below without the need for else
});

其他人的好点是,在发生这样的事件时,您可能希望返回 false 以防止事件冒泡并被其他处理程序捕获。但是,在一般情况下,return;可以很好地使功能短路,并且往往是最清晰的方法。

于 2013-05-30T15:00:33.857 回答
2

使用 Return 语句。

 if(name == call_name){
   //do something
    return;
    }

看看这里(你的警卫声明案例)。

于 2013-05-30T15:00:53.000 回答
2

只需返回 false 以阻止事件进一步冒泡

("#btn").click(function(){
    if(name == call_name){
     alert(err);
     return false;
    }
于 2013-05-30T15:01:29.693 回答