简体   繁体   中英

Copy value of local variable to a global variable in JavaScript

I am trying to update the value of a global variable based on the local variable which is defined inside a function.

I read here on Stack Overflow to use the window object, but still it's not working.

<input type="text" id="getCity" placeholder="Enter"></input>
<button id="btn" type="Submit">Submit</button>
var z = 0;
$('#btn').click(function() {
  window.z = 1
});
console.log(z)

Here is the JSFiddle - https://jsfiddle.net/t18ofd65/8/

You are fundamentally misunderstanding what attaching a click event is doing. This code does not run sequentially line by line

var z = 0;                   // Line 1
$('#btn').click(function() { // Line 2
  window.z = 1               // Line 3
});
console.log(z)               // Line 5

Line 1 executes, followed by line 2. But line 3 does not execute until the button is actually clicked . Line 5 executes immediately after line 2.

If you added a console.log(z) or indeed a console.log(window.z) inside the event handler (ie, after line 3) you would see it actually updates the variable.

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