简体   繁体   English

我如何在if中更改全局变量的值

[英]How do i change the value of a global variable inside of a if

My code does not work, help me please I want to call the function and let it run ON , and when I call it again, the OFF will be executed 我的代码不起作用,请帮我调用该函数,然后让它运行ON ,当我再次调用它时,将执行OFF

 var on = 1; function name () { if(on == 1){ alert('ON'); on = 0; }else if(on == 0){ alert('OFF'); on = 1; } } name(); name(); 

Maybe it's better if you use boolean values to avoid confusion 最好使用布尔值以避免混淆

 <html lang="es"> <head> <title>Helping people at StackOverflow</title> <script> window.onload = function(){ // Start global "on" var in false/true state var on = false; function name (){ if(on != true){ // Set on state on = true; /* Execute "on" code rules */ }else{ // Set off state on = false; /* Execute "off" code rules */ } console.log('Is "ON"?: ',on); } document.getElementById('btn').addEventListener('click',function(){ name(); }); } </script> </head> <body> <input id="btn" type="button" value='Ejecutar'> </body> </html> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM