我有以下开关声明:
switch (result.innerHTML) {
case "":
case " ":
result.innerHTML = "Stage1";
result.style.backgroundColor = "green";
break;
case "Stage1":
result.innerHTML = "Stage2";
result.style.backgroundColor = "red";
break;
case "Stage2":
result.innerHTML = "Stage3";
result.style.backgroundColor = "yellow";
break;
case "Stage3":
result.innerHTML = "Stage4";
result.style.backgroundColor = "pink";
break;
case "Stage4": //start over
result.innerHTML = "";
result.style.backgroundColor = "";
break;
default:
}
在JavaScript中有另一种简洁的方法吗?也许使用数组或JavaScript对象?
答案 0 :(得分:3)
我喜欢这个开关。它易于阅读和理解。有时,较短的代码并不总是更好的代码。
这是另一种选择。
var states {
"": ["Stage1","green"],
" ": ["Stage1","green"],
"Stage1": ["Stage2","red"],
"Stage2": ["Stage3","yellow"],
"Stage3": ["Stage4","pink"],
"Stage4": ["",""]
};
if(result.innerHTML in stages)
{
result.style.backgroundColor = stages[result.innerHTML][1];
result.innerHTML = stages[result.innerHTML][0];
}
答案 1 :(得分:3)
您应该将CSS中的背景颜色放在不同的类(stage1
,stage2
等)中,并将当前阶段存储为单独的变量。
var currentStage = 0;
function proceed() {
currentStage = (currentStage + 1) % 5;
result.innerHTML = currentStage === 0 ? '' : 'Stage' + currentStage;
result.className = 'stage' + currentStage;
}
将来可以提供更清晰的代码。
答案 2 :(得分:0)
有(if,else if和else)语句但是switch语句比它们更清晰。