简体   繁体   中英

Updating a global JS variable with Jquery and return that value

I need to write a function where I can set a global variable in plain js, update it's value with jQuery function and then assign that value that was updated via jQuery function into a normal javasciprt variable.

Here is the code example:

var foo; // global variable in plain js
var bar; // second global variable
jQuery(document).ready(function ($) { 

   // jquery function that updates the variable
   foo = 'updated by jquery' 

 });

bar = foo;

console.log(bar); // console should read 'updated by jquery' but it says undefined

Because you are updating the foo only on ready event but you are tying to log before ready fires

Try this

jQuery(document).ready(function ($) { 
// jquery function that updates the variable
  foo = 'updated by jquery';
  console.log(foo);
});

It won't set the value to 'updated by jquery', because that update will take place when the document is ready, whereas your console.log(foo) is a part of global which will occur previously in sequence than document ready function call.

So, essentially,

var foo; // #1
$(function ($) { 
  foo = 'updated by jquery';
  console.log(foo); // output : updated by jquery //#3
});

console.log(foo); // output : undefined //#2

And the order of execution is #1, #2, #3

So, if you need the updated value, you'll need to access it at point #3 inside document .ready after it has been changed. Or you can raise/trigger an event once the value has been changed using Jquery Events like -

foo='updated';
var event = jQuery.Event( "myEvent" );
$('body').trigger(event);

// The following can now be outside of document ready
$('body').on('myEvent',function(){
   // Access updated foo value here
});

Your code actually should work correctly. But if we use the comments as markers in order (so #2 = "//jquery function that updates the variable"), keep in mind it'll run in the order [#1, #3, #2] because the ready() function will run after the others when the document is ready.

As long as any code that needs foo is running after your ready function, it should read it correctly.

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