简体   繁体   中英

Variable not being assigned value out of function

This code below replaces "amount" with "NaN". I feel like it has something to do with the variable being outside of the add function. Is there any way to get past this basic problem... I feel so dumb right now. Thanks, Matthew.

 var x = 5 var y = 4 function add() { var x = x + y; document.getElementById("amount").innerHTML = x; }
 <p onclick="add()">Hello</p> <p id="amount"> Cacti: 0</p>

I'll accept your answer in a bit, I can't accept that fast, sorry.

This will work:

 <body> <p onclick="add()">Hello</p> <p id="amount"> Cacti: 0</p> <script> var x = 5 var y = 4 function add() { x = x + y; document.getElementById("amount").innerHTML = x; } </script> </body>

Remove var from inside the function, as you don't want to declare a new variable x , but use the x already declared outside the function.

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