简体   繁体   中英

Global variable declared outside function doesn't work

When I am getting number value(document.getelementbyid('number')) outside the function program doesn't work properly - Program displays Fizz all the time. Here is my code

 var number = document.getElementById("number").value; var button = document.getElementById('button'); button.addEventListener('click', function() { if (number % 3 === 0) { alert('Fizz'); } else if(number % 5 === 0) { alert('Buzz'); } else { console.log('..'); } })
 <input type="number" id="number"> <button id="button">+</button>

I want to ask if there's a problem with variable scope? But as I know declared variable outside function should be available inside function because it is Global.

This has nothing to do with the variable or its scope and everything to do with the value you're setting to that variable:

document.getElementById("number").value

When the page first loads and the JavaScript first executes, there is no value in the input. So no value is set to the variable. But when the click event executes its handler function, presumably the user has typed a value into the input.

If you like, you can set a default value for the input:

<input type="number" id="number" value="1">

Then if you get the value when the page first loads it will be "1" . Of course, if you want to get the value entered by the user you'll still have to get that when you want it.

Basically you can't get the value from the user until after the user has entered that value.

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