简体   繁体   中英

jQuery - Return once function finishes

I feel like this is a fairly simple thing, but I can't seem to figure it out. I need a function to return it's value after an action has been completed.

var msg = my_function();
alert(msg);

function my_function(){
  box = $("<div>");
  button = $("<span>submit</span>").click(function(){
    box.remove();
    return "Hello World!";
  });
  $("body").append(box);
} 

However when I do this, it returns msg as 'undefined' before the box is even appended to the body tag. How do I add a 'on complete' or something along those lines to this?

my_function won't wait until the user performs an action. What you are passing to .click() is another function which will be attached as an event handler and executed when the event occurs. This is called asynchronous (and in this case also event-driven) behaviour.

The trick to get the return value you are looking for is to provide your own callback to my_function which will called with that return value when it is available. Note that this callback will be executed any time someone clicks the button (which you have to add to the body, by the way, otherwise it wouldn't show up anywhere):

var myCallback = function(msg) {
    alert(msg);
}

var msg = my_function(myCallback);

function my_function(callback) {
  var box = $("<div>");
  var button = $("<span>submit</span>").click(function(){
    box.remove();
    callback("Hello World!");
  });
  $("body").append(box).append(button);
} 

You put a return in the wrong place. A return statement inside a callback function will do nothing.

var msg = my_function();
alert(msg);

function my_function(){
  box = $("<div>");
  button = $("<span>submit</span>").click(function(){
    box.remove();
    return "Hello World!"; // this return does not make sense
  });
  $("body").append(box);
  return "Hello World!"; // return here what you want

}

I think this is what you want:

my_function(function(msg) { alert(msg); });

function my_function(callbackFn){
  box = $("<div>");
  button = $("<span>submit</span>").click(function(){
    box.remove();
    callbackFn("Hello World!");
  });
  $("body").append(box);
} 

But you should put that span on the page somewhere.

Whatever you want to do, you need to put it into your

click(function() { ... }

. Explanation: This function will only return something after actually the "click" has taken place.

Since your "my_function()" would only return anything (which it does not) after the click, "msg" will always be undefined! -> The "alert" does not wait until "msg" has been assigned ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM