javascript - Call variable from another script in HTML -


i have html file has 1 script declared follows:

<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>   <script type="text/javascript">                           $(document).ready(function() {                                code.......     var = "hello" });                                                </script>               

i trying add script within html file call on variable "a". right now, doing this:

<script type="text/javascript">                                    alert(a);                                                               </script> 

but not alerting anything. if replace string "hello", alerted. calling variable wrong? i've tried searching solutions of them should able call variables script assuming script declared , initialized before. thanks.

move a declaration outside of function.

e.g.,

var a;  $(document).ready(function() {                                code.......     = "hello" });  

and later on...

alert(a); 

remember variables function-scoped, if define inside of function, won't visible outside of function.


update based on comments:

because have timing issue when trying interact a variable, recommend introducing event-bus (or other mechanism) coordinate on timing. given you're using jquery, can create simple bus follows:

var bus = $({});  bus.on('some-event', function() {}); bus.trigger('some-event', ...); 

this lends better code organization, too, since need bus global, , can pass data around in events, rather bunch of other random variables.

e.g.,

var bus = $({});  $(document).ready(function() {                                var = 'hello';     bus.trigger('some-event', { a: }); });  

and in other file:

bus.on('some-event', function(e, data) {     alert(data.a); }); 

jsbin example (obviously not spread across multiple files, same principles apply).


Comments

Popular posts from this blog

Fail to load namespace Spring Security http://www.springframework.org/security/tags -

sql - MySQL query optimization using coalesce -

unity3d - Unity local avoidance in user created world -