简体   繁体   中英

How to return the value of a function after button click in JQuery?

I have a function which returns the output to a promise function when called.

I have a executeScript Method, which dynamically processes Javascript methods and returns a promise as to what those methods return.

Base Skeleton

Ref.executeScript({
                code: "getData(); function getData(){ var res = 'Hello'; return res;}",
            function(results){
     console.log(results); ////THIS RETURNS "Hello"
   });

When the code is directly returning a variable it works. For example, the following returns Hello when executed.

getData();
 function getData(){
   var res = "Hello";
   return res;
  }

But if I return it inside the click event, it returns the previous value "Hello" and not "Hello2" on button click. I want "Hello2" to be returned.

getData();
function getData(){
 var res = "Hello";
 jQuery("#myButton").on('click', function(){
   res = "Hello2";
   alert(res); //this gets called
  });
return res;
}

Updated the Original question to provide more clarity

Of course it still returns "Hello", because when you call that function it does not enter on the click function. What your function really does is setting an action for the click event, but not also calling it. You can't really return a value in a click event function and I can't imagine where would you need it. You can try with out of scope variables like this but I don't recommend doing it:

var hasBeenClicked = false;
jQuery("myButton").on('click', function(){ 
     hasBeenClicked = true;
});

function buttonWasClicked() {
     var res = hasBeenClicked;
     hasBeenClicked = false;
     return res;
});

you should write something like that:

var res = '';
function getData(){
    res = "Hello";
    return res;
}

$(document).ready(function() {
    $("#myButton").click(function(e){
       e.preventDefault(); //if you have form to submit
       res = "Hello2";
    });
});

I think you want to updated value on click event for this you have to use javascript prototype try this

function GetData(){
   this.res = "Hello";

} 
jQuery("#myButton").on('click', function(){

   GetData.prototype.res = "Hello2";
     alert(res); //this gets called
  });
  getData  = new GetData();
  console.log (getData.res)

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