我对如何仅使用 javaScript 编写 switch case 而不是 if 条件感到困惑
I am getting confused about how do i write a switch case instead of the if condition using javaScript only
这是我想使用 switch case 定义的验证函数,但我对如何将此特定代码放入 switch case 感到困惑。
function validation() {
var formrdvalid = false;
var fname = document.getElementById("fname").value;
var city = document.getElementById("city");
var radios = document.getElementsByName("gender");
var agree = document.getElementById("invalidCheck").checked;
if (fname == "") {
alert("please enter firstname");
}
if (city.selectedIndex === 0) {
alert("select the city");
return false;
}
if (!formrdvalid) {
for (var i = 0; i < radios.length; i++) {
if (radios[i].checked) {
formrdvalid = true;
}
}
}
if (!formrdvalid) {
alert( "please select gender");
return false;
}
if(agree === false){
alert("agree terms and conditions");
}
if (!fname||!city || !radios || !agree ) {
return false;
} else {
return true;
}
}
我认为这是可能的。有时(也许不是你的情况)它真的很有用。
为此,您应该声明一个表示整个表单状态的变量,如下所示:
var formrdvalid = false;
var fname = document.getElementById("fname").value;
var city = document.getElementById("city");
var radios = document.getElementsByName("gender");
var agree = document.getElementById("invalidCheck").checked;
// this represents state of the form, including all important info
// like a table
var state = `${formrdvalid}|${fname}|${city}|${radios}|${agree}`;
// now you should just list all valid states
switch(state) {
case `true|myform|London|22|true`:
case VALID_STATE2:
case VALID_STATE3:
return true;
default:
return false;
}
有时定义无效的案例更方便,return true
默认。
这是我想使用 switch case 定义的验证函数,但我对如何将此特定代码放入 switch case 感到困惑。
function validation() {
var formrdvalid = false;
var fname = document.getElementById("fname").value;
var city = document.getElementById("city");
var radios = document.getElementsByName("gender");
var agree = document.getElementById("invalidCheck").checked;
if (fname == "") {
alert("please enter firstname");
}
if (city.selectedIndex === 0) {
alert("select the city");
return false;
}
if (!formrdvalid) {
for (var i = 0; i < radios.length; i++) {
if (radios[i].checked) {
formrdvalid = true;
}
}
}
if (!formrdvalid) {
alert( "please select gender");
return false;
}
if(agree === false){
alert("agree terms and conditions");
}
if (!fname||!city || !radios || !agree ) {
return false;
} else {
return true;
}
}
我认为这是可能的。有时(也许不是你的情况)它真的很有用。
为此,您应该声明一个表示整个表单状态的变量,如下所示:
var formrdvalid = false;
var fname = document.getElementById("fname").value;
var city = document.getElementById("city");
var radios = document.getElementsByName("gender");
var agree = document.getElementById("invalidCheck").checked;
// this represents state of the form, including all important info
// like a table
var state = `${formrdvalid}|${fname}|${city}|${radios}|${agree}`;
// now you should just list all valid states
switch(state) {
case `true|myform|London|22|true`:
case VALID_STATE2:
case VALID_STATE3:
return true;
default:
return false;
}
有时定义无效的案例更方便,return true
默认。