繁体   English   中英

如何在javascript中替换字符串变量的值?

[英]How to replace value of string variable in javascript?

我需要一种在按下按钮时在两种模式之间切换的方法。

我的问题的类比:

按下按钮“开和关”,警报显示“开”或“关”

每次按下检查当前值并替换的按钮时,如何通过更新字符串的值来让字符串在值之间交替:“开”和“关”?

界面

<button onclick="changeState();">Push me</button>

脚本

<script> 

var string = "up"; 

function changeState(){

  if(string=="up"){
  // switching to off
    var string = "down"; // I'm just redeclaring or declaring a new variable right? scope? 
    alert(Off);
    }else{
    // switching to on assuming current state is off
      var string = "up";
      // new state
      alert('on');
    }

  }

}
</script>

这个给你。 我删除 'var' 让它成为全局,同时删除一个}备用:

 var string = "up"; function changeState() { if (string == "up") { // switching to off string = "down"; // I'm just redeclaring or declaring a new variable right? scope? alert("off"); } else { // switching to on assuming current state is off string = "up"; // new state alert('on'); } }
 <button onclick="changeState()">Push me</button>

希望这有帮助。

 var string = "up"; function changeState() { string = string =="up" ? "down" : "up"; }

暂无
暂无

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

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