[英]Turn if/else statement into switch statement
I have found an example on http://www.w3schools.com/ of how to create a responsive navigation bar 我在http://www.w3schools.com/上找到了有关如何创建响应式导航栏的示例
The example has a little bit of JavaScript in the form of a if/else statement. 该示例以if / else语句的形式提供了一些JavaScript。 I would prefer to use a switch statement.
我宁愿使用switch语句。
However, my switch statement does not work when i click the icon and does not provide any errors. 但是,当我单击该图标时,我的switch语句不起作用,并且未提供任何错误。
Example's JS code: 示例的JS代码:
var x = document.getElementById("myTopnav");
if (x.className === "topnav") {
x.className += " responsive";
} else {
x.className = "topnav";
}
My Switch statement: 我的Switch语句:
var x = document.getElementById("myTopnav");
switch (x) {
case "topnav":
x.className += " responsive";
break;
default:
x.className = "topnav";
}
You're comparing x
: 您正在比较
x
:
switch (x)
But the original code is comparing x.className
: 但是原始代码正在比较
x.className
:
if (x.className === "topnav")
Switch on x.clasName
instead: 改为打开
x.clasName
:
switch (x.className)
You are very close! 你很亲密!
Just swap in x.className
in your switch(x)
statement, and you're good to go: 只需在
switch(x)
语句中交换x.className
,就可以了:
var x = document.getElementById("myTopnav");
// use x.className below...
switch (x.className) {
case "topnav":
x.className += " responsive";
break;
default:
x.className = "topnav";
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.