我是JavaScript的初学者并且已经研究了很长一段时间了,我觉得我已经尝试了很多不同的编写代码的方法,它似乎没有按预期工作,什么都没发生。
我想转换这个if语句:
if (browserName == "MSIE") {
} else if (browserName == "IE11+") {
} else if (browserName == "Chrome") {
} else if (browserName == "Firefox") {
} else if (browserName == "Safari") {
} else alert("your browser is not compatible, please use one of these web browsers: Google Chrome, Mozilla Firefox, Internet Explorer or Apple Safari.")
进入switch语句,这就是我目前所拥有的:
switch (browserName) {
case '1': == "MSIE"();
break;
case '2': == "Safari"();
break;
case '3': == "Chrome"();
break;
case '4': == "IE11+"();
break;
case '5': == "Firefox"();
break;
default:
alert("test1");
}
如果它没有检测到浏览器的名称,我只是希望它跳到else警报。 任何帮助将不胜感激。
答案 0 :(得分:2)
case
之后的值应该是您要匹配的值:
switch (browserName) {
case "MSIE":
// do something
break;
case "Safari":
// do something
break;
case "Chrome":
// do something
break;
case "IE11+":
// do something
break;
case "Firefox":
// do something
break;
default:
alert("test1");
break;
}
如果您关注的是值与任何已知值不匹配的情况,您可以将case
堆叠在一起:
switch (browserName) {
case "MSIE":
case "Safari":
case "Chrome":
case "IE11+":
case "Firefox":
break;
default:
alert("test1");
break;
}
答案 1 :(得分:1)
试试这个:
switch (browserName) {
case "MSIE": //Do MSIE work here
break;
case "Safari": //Do Safari work here
break;
case "Chrome": //Do Chrome work here
break;
case "IR11+": //Do IE11+ work here
break;
case "Firefox": //Do Firefox work here
break;
default:
alert("Browser Not Recognized!");
}
答案 2 :(得分:1)
在switch语句中,您无法执行以下操作:
case '1': == "MSIE"();
取而代之的是:
case 'MSIE':
//do code
break;
希望它有所帮助。
答案 3 :(得分:1)
将其转换为switch语句的方法如下:
switch (browserName) {
case "MSIE":
break;
case "Safari":
break;
case "Chrome":
break;
case "IE11+":
break;
case "Firefox":
break;
default:
alert("Your browser is not compatible, please use one of these web browsers: Google Chrome, Mozilla Firefox, Internet Explorer or Apple Safari.");
}
你也可以这样做:
switch (browserName) {
case "MSIE":
case "Safari":
case "Chrome":
case "IE11+":
case "Firefox":
default:
alert("Your browser is not compatible, please use one of these web browsers: Google Chrome, Mozilla Firefox, Internet Explorer or Apple Safari.");
}
但做这样的事情可能会更好:
function checkBrowser(browserName) {
var compatibleBrowsers = ['MSIE', 'Safari', 'Chrome', 'IE11+', 'Firefox'];
if (compatibleBrowsers.indexOf(browserName) !== -1) { return; }
alert("Your browser is not compatible, please use one of these web browsers: Google Chrome, Mozilla Firefox, Internet Explorer or Apple Safari.");
}