Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/440.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何替换javascript中字符串变量的值?_Javascript - Fatal编程技术网

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

如何替换javascript中字符串变量的值?,javascript,Javascript,当按下按钮时,我需要一种在两种模式之间切换的方法 我的问题的类比: 按下按钮“开”和“关”,警报显示“开”或“关” 如何通过每次按下检查当前值并替换的按钮时更新字符串的值,使字符串在值“开”和“关”之间切换 接口 <button onclick="changeState();">Push me</button> 推我 脚本 <script> var string = "up"; function changeState(){ if(strin

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

我的问题的类比:

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

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

接口

<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 string=“up”;
函数changeState(){
如果(字符串==“向上”){
//关闭
var string=“down”//我只是重新声明或声明一个新变量,对吗?范围?
警报(关闭);
}否则{
//假设当前状态为off,则切换到on
var string=“up”;
//新国家
警报(“开启”);
}
}
}

给你。我删除'var'使其成为全局的,同时删除一个
}
备用:

var string=“up”;
函数changeState(){
如果(字符串==“向上”){
//关闭
string=“down”//我只是重新声明或声明一个新变量,对吗?范围?
警报(“关闭”);
}否则{
//假设当前状态为off,则切换到on
string=“up”;
//新国家
警报(“开启”);
}
}
推送我
var string=“up”;
函数changeState(){
字符串=字符串==“向上”?“向下”:“向上”;

}
这显然有效,但我不确定我这边到底出了什么问题。谢谢。奇怪的是,第二个条件是“else if”。没关系,但没必要。如果你有另一种状态,例如向上、向下、断开,那么使用else If或switch case语句。我所说的“推”和“类比”是指一个按钮,这个人会用手指或类似于电灯开关的开关来推动。三元变量或类似的东西,前几天有人向我展示了这一点。谢谢你的回答。