[英]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.