[英]How to replace value of string variable in javascript?
I need a way to switch between two modes when a button is pressed.我需要一种在按下按钮时在两种模式之间切换的方法。
The analogy of my problem:我的问题的类比:
A button is pushed "on and off" and an alert says "On" or "Off"按下按钮“开和关”,警报显示“开”或“关”
How do I get string to alternate between the values: "On" and "Off" by updating the value of string every time I push the button which checks current value and replaces?每次按下检查当前值并替换的按钮时,如何通过更新字符串的值来让字符串在值之间交替:“开”和“关”?
interface界面
<button onclick="changeState();">Push me</button>
script脚本
<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>
Here you are.这个给你。 I remove 'var' let it global, also remove a
}
spare:我删除 '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>
Hope this help.希望这有帮助。
var string = "up"; function changeState() { string = string =="up" ? "down" : "up"; }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.