简体   繁体   中英

Passing variables in nested functions between scripts

I am a newbie to jQuery and am trying to make a variable within a nested function available between scripts. However, I am unsure of how to do so (I am pretty bad at understanding scope). Here is the code (note: I copy-pasted this from jsFiddle, hence some tags are purposefully missing).

<body>
    <h1>Hello</h1>    
    <button id="btn">click</button>
 <script>
    var x;
    $(document).ready(function() {
        $(document).on("click", "#btn", function() {
           x = "hello world";
        });
    });
</script>
<script>
    alert(x);
</script>    
</body>

Any help is appreciated!

for that alert to alert Hello World you need to add it inside the click function... since x is redeclare inside the click event . and you don't have to seperate your <script> .

<script>
var x;
$(document).ready(function() {
    $(document).on("click", "#btn", function() {
       x = "hello world";
       alert(x); //alerts hello world
    });
    alert(x); //alerts undefined since x is not set as this is executed before the click event as soon as document is ready
});
alert(x); //alerts undefined since x is not set


</script>    

You are doing correctly, in your code <script> alert(x);</script> when you are using alert x value is not set.

HTML:

<button id="set">set</button>
<button id="get">get</button>

JS:

var x;
$(document).ready(function () {
    $(document).on("click", "#set", function () {
        x = "hello world";
    });

    $(document).on("click", "#get", function () {
        alert(x);
    });
});

JSFiddle Demo

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