开发者

jquery: returning true or false [duplicate]

This question already has an answer here: Closed 11 years ago.

Possible Duplicate:

How do you know when to return false from a jQuery function?

We开发者_运维问答 all have some jquery code that looks like this:

$('#MySelector').somefunction(function () {

   // do something

});

Is there a benefit/penalty for including a return statement and should we return true or false? For now, I'd say my code works fine without the return statements but I was wondering what would a return statement do in the context I described.

Thanks for your clarifications.


For return false, this is a good read, jQuery Events: Stop (Mis)Using Return False.


You're passing the anonymous function as a parameter to somefunction, so it really depends on what somefunction does with that parameter. What really matters is what somefunction returns. For example, let's say this is how it's defined:

$.fn.somefunction = function ( fnParam ) {
  var returnVal = fnParam();

  if (returnVal) {
    // do something
  } else {
    // do something else
  }

  return this;
};

So here we assign the return value of fnParam to a variable and use that variable to determine actions within somefunction. somefunction returns this though, which would be the jQuery object that it was passed (in your example $('#MySelector')). Since you return this, somefunction can chain with other jQuery methods like:

$('#MySelector').somefunction(function(){ // blah })
                .css('background','yellow')
                .appendTo('body')
                .show();


in this case, if you use

return false;

it aborts that function(){ } and continues if possible


Returning something is only beneficial if you want to exit out of the function prematurely and/or if you need to assign the value of the function's result to a variable:

var foo = calculate(1,2); // foo = 3

function calculate(a,b){
    return a+b;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜